oop - Multiple-inheritance and mixins to bind object slots in Python -
i interested in creating class hierarchy various mixins create slots in object:
class a(object, keyable, taggable): """a keyable , taggable.""" def __init__(self): super(a, self).__init__() print "a" class b(bodytext, valuable): """b a is, plus valuable""" def __init__(self): super(b, self).__init__() print "b" class c(bodykey, posable): """c b is, plus posable""" def __init__(self): super(c, self).__init__() print "c"
however, when attempt run code (along mixins below) error """ cannot create consistent method resolution order (mro) bases keyable, taggable, object """
if there different way achieve goals (such composition or whatever) open it.
# begin mixins class posable(object): def __init__(self): super(posable, self).__init__() self.pos = 0 print "posable" class keyable(object): def __init__(self): super(keyable, self).__init__() self.key = '' print "keyable" class taggable(object): def __init__(self): super(taggable, self).__init__() self.tag = '' print "taggable" class valuable(object): def __init__(self): super(valuable, self).__init__() self.val = 0 print "valuable" # end mixins
try putting mixins first:
class a(keyable, taggable, object): ...
actually, in case, since of mixins inherit object
, don't need again:
class a(keyable, taggable): ...
the error comes because when write:
class a(object, keyable, taggable): ...
you're telling python keyable
comes before taggable
comes before object
in method resolution order (left right). of course, when python constructs method resolution order, there more things inserted between, @ end of day, mro guaranteed this:
[a, object, ... keyable, ..., taggable, ...]
where ...
can 0 or more classes. unforunately, in case, python can't construct mro because keyable
(and taggable
) inherit object (which tells python need come before object
in mro).
Comments
Post a Comment