Class variable inheritance

Terry Reedy tjreedy at udel.edu
Wed Sep 16 19:40:22 EDT 2009


Duncan Booth wrote:
> 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).

The documentation for this, with an example, is in RefMan 3.3.3,
Customizing Class Creation. See the metaclass .__prepare__ method.




More information about the Python-list mailing list