Hrvoje T Hrvoje T -4 years ago 107
Python Question

Passing a variable between two methods in Python?

(I am trying to learn Python by myself and I am not a native english speaker.)

I need an advice. What is a usual way to pass a variable in OOP from one method to another? Is it better to make a variable an attribute of a instance, to make a helper 'get' function or something else?

1.

class A(object):
...

def a(self):
self.first = 32
second = input("Second:")
return self.first + second

def b(self):
return self.first + 1


..or

class A(object):
...

def get_first(self):
first = 32
return first

def a(self):
first = get_first()
second = input("Second:")
return first + second

def b(self):
return get_first() + 1


or is there some other usual way?

Answer Source

It depends. The advantage with using a getter method is that, if the field changes, you don't have to change the functions using it. However, in Python, there is no point to do that, because of properties. You can start by storing self.first as a variable of the instance. If it changes, you can add a @property named first. Then, all the functions refering to self.first will get it through this getter method instead. So, for python in particular, go with the first option.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download