Union of class variables

Ben Finney ben+python at benfinney.id.au
Tue Feb 16 10:01:08 CET 2010

Joan Miller <peloko45 at gmail.com> writes:

> Is possible to get a third class with the class variables of another
> two classes?

Multiple inheritance is allowed in Python:

    class Baz(Foo, Bar):

However, it leads to complications that you likely don't want, e.g.

Is it *really* the case that the new class is best expressed by an IS-A
relationship to *both* the others? (“Every Baz IS-A Foo; every Baz IS-A

You should consider composition, instead. Decide which other class
represents the more general case of the new class, and give it
additional capabilities through a HAS-A relationship. (“Every Baz IS-A
Foo; every Baz HAS-A Bar”)

    class Baz(Foo):

        def __init__(self):
            self.bar = Bar()

That way, you keep the clarity of single inheritance and additional
capabilities are accessed through an attribute.

 \        “Always code as if the guy who ends up maintaining your code |
  `\     will be a violent psychopath who knows where you live.” —John |
_o__)                                                         F. Woods |
Ben Finney

More information about the Python-list mailing list