Python: variables, inheritance, and default arguments

I think I have some misunderstandings about using "class" and "inheritance" in Python. I will simplify my question as follows:

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 will go wrong as shown below:

 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' for self.data, which is 100. Without a β€œclass” this will be much simpler:

 data = 100 def d(num = data): print num >>>d() >>>100 

I have already collected some articles, but still stuck in this problem ... Thanks in advance!

+4
source share
6 answers

When you do this:

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

you are 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 can see, the python compiler does not know what the second num .

But nothing prevents 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 
+9
source

This has nothing to do with inheritance. You can try to do the same in base class A , and it will fail in the same way.

To achieve what you want, just do:

 def c(self, num=None): if num is None: num = self.data 
+3
source

The default value of the parameter is evaluated when the function is defined, and not when it is called. There is no self name during the definition.

The best course is to use None by default, and then use a function in a function to interpret what it means:

 class C(A): def c(self, num=None): if num is None: num = self.data #.. the rest of the function .. 
+2
source

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

Why do you want to do what you do?

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

The method of your class receives arguments; you cannot pass by itself. something.

0
source

As already mentioned, you cannot use the "self" variable. If you do not need to change the data value later, you can do the following:

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

Source: https://habr.com/ru/post/1396635/


All Articles