Reputation: 1027
class foo():
def __init__(self,a):
self.A=a
def foo2(self,aa=self.A):
return "la"
@classmethod
def test(cls):
d=foo()
d.foo2()
The memberfunction foo2 cannot find self.A nor A. Is it because A is not globally set inside the class?
Upvotes: 2
Views: 83
Reputation: 4937
Keyword arguments, such as aa
, cannot take on a default value from self
. Keyword arguments are evaluated when the method is defined, not when it is called. Typically one would achieve what you're trying by setting the default of aa
to None
:
class foo():
def __init__(self, a):
self.A = a
def foo2(self, aa=None):
if aa is None:
aa = self.A
return 'la'
Note also that since keyword argument defaults are evaluated at definition, not execution, all invocations of foo2
share their default argument even if called from different instances of foo
. This often trips up new Python programmers when working with methods such as:
def footoo(a=list()):
a.append(1)
return a
All calls to footoo will get the same list object; not a new one at each call. So calling footoo
repeatedly will result in the following:
>>> footoo()
[1]
>>> footoo()
[1, 1]
>>> footoo()
[1, 1, 1]
Upvotes: 4
Reputation: 500843
The error occurs when the default value is evaluated. This happens when the class is being defined (not when the method is called). At that point in time, self
has no meaning.
One way to fix this is like so:
...
def foo2(self,aa=None):
if aa is None:
aa = self.A
return "la"
...
Upvotes: 0
Reputation: 39913
You are right, you can't do that.
For example, in Python, you have to be very careful about this because it will use the same list over and over (in this case, it will continue appending to the same list):
def foo2(self,aa=[]):
aa.append('foo')
return "la"
Instead, a very common approach is to assign None
as the default value, and then have an if-statement to set it inside the function:
def foo2(self,aa=None):
if not aa:
aa = self.A
return "la"
Upvotes: 0