Class variable inheritance

Carl Banks pavlovevidence at gmail.com
Tue Sep 8 20:44:01 EDT 2009


On Sep 8, 4:50 pm, HPJ <henrypija... at gmail.com> 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 A.foo. So the method itself will be
> be copied, but its address stored separately in A.foo and B.foo.


No, I'm afraid not.  Here is what happens.  Conceptually, Python
checks for the presence of B.foo, 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

A.foo = 2

print B.foo  # what should this print, 1 or 2?


You could argue that copying class attributes (so that B.foo 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