How to avoid parallel class hierarchy in python

前端 未结 3 1811
太阳男子
太阳男子 2021-01-21 04:19

I\'ve been running into a weird little smell in my python code lately and I think it has something to do with parallel inheritance. Here is a small example I concoc

3条回答
  •  深忆病人
    2021-01-21 04:29

    This might be going too far afield, but I don't see the need for a separate DogHabits class. habits should be a class attribute, not an instance attribute, and could be set by __init_subclass__.

    class Dog:
        habits = ['lick butts']
    
        def __init_subclass__(cls, habits=None, **kwargs):
            super().__init_subclass__(**kwargs)
            if habits is not None:
                cls.habits = cls.habits + habits
    
    
    class GermanShepherd(Dog, habits=['herd sheep']):
        def __init__(self):
            self.type = 'german shepherd'
    
    
    class Labrador(Dog, habits=['pee on owner']):
        def __init__(self):
            self.type = 'labrador'
    

    type itself is also more of a class attribute than an instance attribute, as it's simply an (alternate) string representation of information already encoded by the class itself. Since you wouldn't append to an existing value, it's easier to just set the class attribute where necessary rather than going through __init_subclass:

    class Dog:
        habits = ['lick butts']
        type = 'generic_dog'
    
        def __init_subclass__(cls, habits=None, **kwargs):
            super().__init_subclass__(**kwargs)
            if habits is not None:
                cls.habits = cls.habits + habits
    
    
    class GermanShepherd(Dog, habits=['herd sheep']):
        type = 'german shepard'
    
    
    class Labrador(Dog, habits=['pee on owner']):
        type = 'labrador'
    
    
    class BlackLabrador(Labrador):
        pass  # E.g. if you are happy with inheriting Labrador.type
    

提交回复
热议问题