简体   繁体   中英

Multiple-inheritance and mixins to bind object slots in Python

I am interested in creating a class hierarchy where various mixins create the slots in an object:

class A(object, Keyable, Taggable):
    """A is keyable and taggable."""
    def __init__(self):
        super(A, self).__init__()
        print "A"

class B(BodyText, Valuable):
    """B is everything a A is, plus Valuable"""
    def __init__(self):
        super(B, self).__init__()
        print "B"

class C(BodyKey, Posable):
    """C is everything a B is, plus Posable"""
    def __init__(self):
        super(C, self).__init__()
        print "C"

However, when I attempt to run this code (along with the mixins below) I get the error """ Cannot create a consistent method resolution order (MRO) for bases Keyable, Taggable, object """

If there is a different way to achieve my goals (such as composition or whatever) I am open to 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 the mixins first :

class A(Keyable, Taggable, object):
    ...

Actually, in this case, since all of your mixins inherit from object , you really don't need to again:

class A(Keyable, Taggable):
    ...

The error comes because when you write:

class A(object, Keyable, Taggable):
   ...

You're telling python that Keyable comes before Taggable which comes before object in the Method Resolution order (left to right). Of course, when python constructs the method resolution order, there could be more things inserted between, but at the end of the day, the mro is guaranteed to look like this:

[A, object, ...  Keyable, ..., Taggable, ...]

where the ... can be 0 or more classes. Unforunately, in this case, python can't construct that mro because Keyable (and Taggable ) inherit from object (which tells python that they need to come before object in the mro).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM