Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 401
amigcamel Avatar asked Feb 15 '12 14:02

amigcamel


3 Answers

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
like image 162
Rik Poggi Avatar answered Oct 18 '22 04:10

Rik Poggi


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
like image 39
Bogdan Avatar answered Oct 18 '22 04:10

Bogdan


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 ..
like image 2
Ned Batchelder Avatar answered Oct 18 '22 05:10

Ned Batchelder