How to avoid parallel class hierarchy in python

前端 未结 3 1812
太阳男子
太阳男子 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:30

    This answer assumes that the DogHabits is much more complex than a mere list and is really worth a dedicated class with its own inheritance.

    On a design point of view, I can see a first question on whether habits and type should be class or instance members. Here again, this answer assumes that there are reasons to make them instance members.

    I would make Habits an inner class of Dogs and state in the class documentation that is can be customized by building a subclass of it in a subclass of Dogs:

     class Dog:
        class Habits:
            """Represents the habits of a Dog.
    
            It can be customized in a child class by creating in the subclass an
            inner class named Habits that would be a subclass of Dog.Habits
            """
    
            def __init__(self):
                self.habits = ['lick butt']
    
        def __init__(self, typ='generic_dog'):
            self.type = typ
            self.my_habits = self.__class__.Habits()
    
        def do_stuff(self):
            for habit in self.my_habits.habits:
                print(habit)
    
    
    class GermanShepherd(Dog):
    
        class Habits(Dog.Habits):
    
            def __init__(self):
                super().__init__()
                self.habits.extend(['herd sheep'])
    
        def __init__(self):
            super().__init__('german shepherd')
    
    
    class Labrador(Dog):
    
        class Habits(Dog.Habits):
            def __init__(self):
                super().__init__()
                self.habits.extend(['hunt', 'pee on owner'])
    
        def __init__(self):
            super().__init__('labrador')
    

提交回复
热议问题