[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.python

mixins and new style classes

mk

2/17/2010 6:01:00 PM

>>> class Person(object):
.... pass
....
>>> class Friendly(object):
.... def hello(self):
.... print 'hello'
....
>>>
>>> Person.__bases__ += (Friendly,)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Cannot create a consistent method resolution
order (MRO) for bases object, Friendly




But it works for old-style classes:


>>> class Person:
.... pass
....
>>> class Friendly:
.... def hello(self):
.... print 'hello'
....
>>>
>>> p = Person()
>>>
>>> Person.__bases__ += (Friendly,)
>>>
>>> p.hello()
hello


Python is 2.6.1.

1 Answer

Bruno Desthuilliers

2/17/2010 8:32:00 PM

0

mk a écrit :
>>>> class Person(object):
> ... pass
> ...
>>>> class Friendly(object):
> ... def hello(self):
> ... print 'hello'
> ...
>>>>
>>>> Person.__bases__ += (Friendly,)
> Traceback (most recent call last):
> File "<stdin>", line 1, in <module>
> TypeError: Cannot create a consistent method resolution
> order (MRO) for bases object, Friendly

Indeed. After the addition of Friendly to Person.__bases__, the mro for
Person would be (Person, object, Friendly). But the mro for Friendly is
(Friendly, object). This is not consistent. The right solution would be
to inject Friendly before object, ie:

Person.__bases__ = (Mixin, object)

Now the bad news is that this fails too:

TypeError: __bases__ assignment: 'Mixin' deallocator differs from 'object'

The above problem is not new, and had been discussed here:

http://bugs.python.org/i...

....and it's still unresolved AFAICT :-/

OTHO, the concrete use case for such a feature seem to be rather uncommon.

>
>
> But it works for old-style classes:

Old-style classes are a very different beast.