Class variable inheritance

Carl Banks pavlovevidence at
Wed Sep 9 02:44:01 CEST 2009

On Sep 8, 4:50 pm, HPJ <henrypija... at> wrote:
> > would you expect the B class to have a copy of the foo method?
> Sorta. I would expect B to have a copy of the "foo" attribute, which
> then refers to the same method as So the method itself will be
> be copied, but its address stored separately in and

No, I'm afraid not.  Here is what happens.  Conceptually, Python
checks for the presence of, and if it's not there it checks for
foo's presence in the base classes.  (In actuality Python premaps
attributes to the approprirate base class, so only two dict lookups
are necessary.)

Python is a very dynamic langauge which allows you to modify class
objects at runtime.  So if you inherit from a class, then later modify
that class, what should happen?

class A(object):
    foo = 1

class B(A):
    pass = 2

print  # what should this print, 1 or 2?

You could argue that copying class attributes (so that would be
1) is a reasonable way to do inheritance, but IMO the referencing
attributes in base classes reflects the underlying concept of
inheritance better.

Carl Banks

More information about the Python-list mailing list