Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #4277
| Newsgroups | comp.lang.python |
|---|---|
| Date | 2011-04-28 15:35 -0700 |
| Subject | Re: Composition instead of inheritance |
| From | Carl Banks <pavlovevidence@gmail.com> |
| Message-ID | <mailman.967.1304030151.9059.python-list@python.org> (permalink) |
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):
>
> http://code.activestate.com/recipes/577658-composition-of-classes-instead-of-multiple-inherit/
>
> 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:
class MakeSureNoBasesHaveTheSameClassAttributesMetaclass(type):
def __new__(metatype,name,bases,dct):
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")
return type.__new__(metatype,name,bases,dct)
Carl Banks
Back to comp.lang.python | Previous | Next — Next in thread | Find similar | Unroll thread
Re: Composition instead of inheritance Carl Banks <pavlovevidence@gmail.com> - 2011-04-28 15:35 -0700
Re: Composition instead of inheritance Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2011-04-29 02:31 +0000
Re: Composition instead of inheritance Ben Finney <ben+python@benfinney.id.au> - 2011-04-29 13:50 +1000
Re: Composition instead of inheritance Dennis Lee Bieber <wlfraed@ix.netcom.com> - 2011-04-28 20:57 -0700
csiph-web