Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reference a base class' attribute in derived class?

Tags:

python

I can do this:

class Blah2:
    atttr = 5
    aa = atttr


ob = Blah2
print(ob.aa)

http://ideone.com/pKxMc2

So I assumed I could as well do this:

class Blah1:
    atttr = 5


class Blah2(Blah1):
    aa = atttr


ob = Blah2
print(ob.aa)

Nope I can't: http://ideone.com/6HS1MO

SPits out the following error:

Traceback (most recent call last):
  File "./prog.py", line 5, in <module>
  File "./prog.py", line 6, in Blah2
NameError: name 'atttr' is not defined

Why doesn't this work and how to make it working?


1 Answers

The class block scope only exists temporarily during class definition. After class definition, you would have to access that attribute via the class object, i.e. Blah1.atttr.

This is documented under the execution model section.

Class definition blocks and arguments to exec() and eval() are special in the context of name resolution. A class definition is an executable statement that may use and define names. These references follow the normal rules for name resolution with an exception that unbound local variables are looked up in the global namespace. The namespace of the class definition becomes the attribute dictionary of the class. The scope of names defined in a class block is limited to the class block; it does not extend to the code blocks of methods – this includes comprehensions and generator expressions since they are implemented using a function scope.

like image 156
wim Avatar answered Feb 27 '26 21:02

wim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!