Class variable inheritance

Duncan Booth duncan.booth at invalid.invalid
Wed Sep 16 08:10:12 EDT 2009


Lie Ryan <lie.1296 at gmail.com> wrote:

> Terry Reedy wrote:
>> Lie Ryan wrote:
>> 
>>>
>>> Note that when the python interpreter meets this statement:
>>>
>>> class B(P):
>>>     def foo(self):
>>>         print('ab')
>>>     X = 'f'
>>>
>>> the compiler sees a class statement -> create a new blank class
>>>                                     -> assign P as the new class'
>>>                             parent 
>> 
>> No, it saves the name 'B' and bases tuple P, and create a new *dict*,
>> call it d here though it is anonymous as far as the class body is 
>> concerned.
> 
> Neat, I'd never thought that it creates the ".__dict__" before the
> class itself.
> 
It has to be that way: some of the internal methods cannot be modified 
after the initial creation of the class, so you need to use a namespace 
that exists before the class itself exists.

The situation changes slightly in Python 3 where the metaclass can hook 
into the creation of the dict and instead create any kind of object which 
exposes a dict-like interface. That opens the door to classes where the 
order in which the order attributes are defined is significant or even 
where you can give multiple definitions for the same attribute (e.g. to 
support overloaded methods).


-- 
Duncan Booth http://kupuguy.blogspot.com



More information about the Python-list mailing list