I think I have some misunderstandings of the usage of "class" and "inheritance' in Python. I'll simplify my question as the followings:
class A:
def __init__(self):
self.data = 100
class B(A):
def b(self):
print self.data
>>>B().b()
>>>100
OK, so far so good. However, if I create another class, something goes wrong, which is shown as the following:
class C(A):
def c(self, num=self.data):
print self.data
>>>C().c()
NameError: name 'self' is not defined
I want to set the default value of 'num' to self.data, which is '100'. Without 'class', it will be much simpler:
data = 100
def d(num = data):
print num
>>>d()
>>>100
I've already googled some articles, but still stuck in this problem... Thanks in advance!
When you do this:
class C(A):
def c(self, num=self.data):
print self.data
you're doing something like:
>>> def d(num, data=num):
... print(num, data)
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'num' is not defined
And as you see the python compiler does not know what the second num
is.
But there's nothing stopping you from doing something like:
class C(A):
def c(self, num=None):
print num or self.data
or with an explicit None
check:
class C(A):
def c(self, num=None):
if num is None:
num = self.data
print num
This has nothing to do with inheritance. You can try to do the same in the base class A
and it would fail in the same way.
For achieving what you want simply do:
def c(self, num=None):
if num is None:
num = self.data
Function parameter defaults are evaluated when the function is defined, not when it is called. At definition time, there is no name self
.
The best course is to use None as a default, and then use logic in the function to interpret what that means:
class C(A):
def c(self, num=None):
if num is None:
num = self.data
#.. the rest of the function ..
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With