Reputation: 3913
(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?
Upvotes: 0
Views: 107
Reputation: 51
I usually use (1) but make sure self.first is properly defined if you call b before a.
If you use (2), try to make get_first as efficient as possible to avoid computing twice the same thing.
Upvotes: 1
Reputation: 29071
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.
Upvotes: 1