Python class inside subclass inheriting from class inside parent class
标题几乎是不言自明的,但我认为这可以用一个例子来更好地解释。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | class Dog(): def __init__(self, name): self.name = name def get_name(self): return self.name def get_color(self): return body_color() class personality_1(): def get_happiness(self): return happiness_with_owner() def get_sadness(self): return sadness() ## A lot more personality methods here class SocialDog(Dog): # Override regular method def get_color(self): return face_color() # I want to override the personality 1 class but not completely, just one method class personality_2(>>>How to inherit from personality_1?<<<): # Now, I would like to override just one method of personality 1: def get_happiness(self): return happiness_with_others() |
希望逻辑是正确的。我试图使用super(),但没有成功。希望我可以在不使用对父类的显式调用的情况下找到解决方案。
有什么想法吗?
事先谢谢!
使用的名字外舱内舱:到达
1 2 3 | class SocialDog(Dog): class personality_2(Dog.personality_1): # ... |
这是说,这是一个非常奇怪的事情,你做的,隐藏在狗的性格类的类,然后使用他们的工作……
如果一个人是tightly耦合到一类或类特异性
或者,如果它真的不重要,那么这是狗的个性,为什么不离开在模块层次上人格类,在那里他们可以instantiated和任何其他类继承的类?你会
1 2 3 4 5 6 7 8 9 10 11 12 13 | class WolfPersonality(DogPersonality): # ... class Wolf(Dog): def __init__(self, personality=None): if personality is None: personality = WolfPersonality() self.personality = personality # ... # Later... wolf = Wolf() wolf_puppy = Wolf(FriendlyDogPersonality()) |
从酒店到你指定的等级,根据你提供的代码是必需的,所有的类的定义是这样的:
1 2 3 4 | class SocialDog(Dog): #... class personality_2(Dog.personality_1): #... |
现在的问题是,当试图使用
1 2 3 4 | class Dog(object): #... class personality_1(object): #... |
然后你可以把
1 2 | super(SocialDog.personality_2, self).super_class_method() super(SocialDog.personality_2, self).super_class_field |