Composition instead of inheritance
pavlovevidence at gmail.com
Thu Apr 28 18:35:47 EDT 2011
On Thursday, April 28, 2011 10:15:02 AM UTC-7, Ethan Furman wrote:
> For anybody interested in composition instead of multiple inheritance, I
> have posted this recipe on ActiveState (for python 2.6/7, not 3.x):
> Comments welcome!
That's not what we mean by composition. Composition is when one object calls upon another object that it owns to implement some of its behavior. Often used to model a part/whole relationship, hence the name.
The sorts of class that this decorator will work for are probably not the ones that are going to have problems cooperating in the first place. So you might as well just use inheritance; that way people trying to read the code will have a common, well-known Python construct rather than a custom decorator to understand.
If you want to enforce no duplication of attributes you can do that, such as with this untested metaclass:
u = collections.Counter()
for base in bases:
for key in base.__dict__.keys():
u[key] += 1
for key in dct.keys():
u[key] += 1
if any(u[key] > 1 for key in u.keys()):
raise TypeError("base classes and this class share some class attributes")
More information about the Python-list