简体   繁体   中英

Python: variables, inheritance, and default arguments

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 ..

You are misunderstanding class methods. Class methods are implicitly passed self. Self does not exist def c(self, num=HERE>>>>>self<<<<<HERE.data):

Why do you want to do what you are doing?

class C(A):
    def c(self,data=None):
        if data == None:
            print self.data
        else 
            print data 

The method of your class get arguments, you cannot pass self.something.

As already mentioned, you can't use 'self' variable like that. If you don't have to change the value of data later, you can do following:

class A:
    data = 100

class C(A):
    def me(self, num=A.data):
        print num

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM