英文:
inheritance with parent class specialization
问题
对不起,如果我很难理解,英语不是我的母语。
我正在尝试创建一个从专门化的父类派生的小狗类,但不知道它将继承哪个父类。同时,给小狗类提供一组要实现的抽象方法。
from abc import ABC, abstractmethod
class DogSkillSet(ABC):
@abstractmethod
def bark(self):
raise NotImplementedError
@abstractmethod
def chase(self):
raise NotImplementedError
@abstractmethod
def fetch(self):
raise NotImplementedError
class Dog:
def __new__(cls, race, **kwargs):
if race == 'sheperd':
return GermanSheperd()
elif race == 'rott':
return Rottweiller()
class GermanSheperd:
def __init__(self):
self.race = "sheperd"
class Rottweiller:
def __init__(self):
self.race = "rott"
class Puppy(Dog, DogSkillSet):
def __init__(self, race):
super().__init__(race)
def bark(self):
print("small woof")
def chase(self):
print("stare into the air")
def fetch(self):
print("stare into the air")
def play(self):
print('playing')
if __name__ == '__main__':
my_dog = Puppy('berger')
my_dog.bark()
但在专门化之后继承不会发生。你能告诉我我做错了什么吗?
英文:
I'm sorry if I'm hard to understand, English is not my first language.
I'm trying to have a Puppy class derived from a specialize parent class, but without knowing which parent class it will inherit. And at the same time, give the Puppy class a set of abstract methods to implement.
from abc import ABC, abstractmethod
class DogSkillSet(ABC):
@abstractmethod
def bark(self):
raise NotImplementedError
@abstractmethod
def chase(self):
raise NotImplementedError
@abstractmethod
def fetch(self):
raise NotImplementedError
class Dog:
def __new__(cls, race, **kwargs):
if race == 'sheperd':
return GermanSheperd()
elif race == 'rott':
return Rottweiller()
class GermanSheperd:
def __init__(self):
self.race = "sheperd"
class Rottweiller:
def __init__(self):
self.race = "rott"
class Puppy(Dog, DogSkillSet):
def __init__(self, race):
super().__init__(race)
def bark(self):
print("small woof")
def chase(self):
print("stare into the air")
def fetch(self):
print("stare into the air")
def play(self):
print('playing')
if __name__ == '__main__':
my_dog = Puppy('berger')
my_dog.bark()
But the inheritance doesn't happen after the specialization. Could you tell me what I am doing wrong.
答案1
得分: 1
以下是已翻译的内容:
你的 Dog.__new__
,被 Puppy
继承,返回 GermanShepherd
或 Rottweiler
的实例,它们都不继承自 DogSkillSet
(或者说不继承自 Dog
)。
英文:
Your Dog.__new__
which is inherited by Puppy
, returns instances of GermanShepherd
or Rottweiler
, neither of which inherit from DogSkillSet
(or Dog
for that matter)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论