Class variable inheritance

  • Thread starter Henry 'Pi' James
  • Start date
T

Terry Reedy

Lie said:
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.
-> *execute* the class' body

with the new dict d as the local namespace. In other words, the
equivalent of

exec('''body''', globals(), {}) # new Py3 exec() form
# new context
the compiler sees a def statement -> *compile* the def's body

to a code object which is then attached to a function object
-> assign the compiled body to B.foo

No said:
the compiler sees X = 'f' statement -> assign 'f' to B.X

No, d['X'] = 'f'
# exit the new context

Up to this point, there is no new class object.
-> assign the new class to B

It calls meta(name, bases, d), where meta is the metaclass 'type' by
default but can be any callable which does anything, though the
intention is that it be a subclass of type or at least something that
creates a class object, and that d become the backstage attribute dict
for the result.
Your problem is related to how the interpreter *execute* a class
definition rather than the name resolution.

Terry Jan Reedy
 
L

Lie Ryan

Terry said:
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.
 
T

Terry Reedy

Duncan said:
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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,787
Messages
2,569,627
Members
45,329
Latest member
InezZ76898

Latest Threads

Top