inheriting variables

Alex Martelli aleax at aleax.it
Thu Apr 17 11:14:50 EDT 2003


Haran Shivanan wrote:

> This seems like a fairly straight forward thing but I'm not sure about how
> to implement it.
> I have a base class from which I'm deriving several new classes:
> class A:
> mem_a=0
> mem_b=1
> class B(A):pass
> 
> I want B to inherit mem_a and mem_b from A without my having to explicit
> do something like:

That is exactly how Python's inheritance works!  Have you tried it?

>>> class A:
...   mema = 23
...   memb = 45
...
>>> class B(A): pass
...
>>> B.mema
23
>>> B.memb
45
>>>


We're talking about CLASS attributes here.  If you're confused between
class attributes and instance attributes (the latter being the kinds
that's typically assigned in __init__), then the right approach is to
ensure that A has a constructor (__init__) and each derived class uses
the base class's constructor (by not overriding it, or by explicitly
calling it if it does override it with its own __init__), which again
is the normal Pythonic way of doing things (doesn't necessarily happen
automatically, but when it doesn't you make it happen explicitly).


Alex





More information about the Python-list mailing list