如何两个父类的函数都使用
我的代码是这样写的,我把 Sperker() 中的 speak 函数重命名为 speak1 ,现在想要两个父类的函数都使用,该怎么写呢?我感觉是实例化的时候传参数不对,是哪里不对,应该怎么写?
class People(object): def __init__(self, name, age): self.name = name self.age = age def speak(self): print(f'{self.name}说: 我{self.age}岁') class Speaker(object): def __init__(self, name, career, topic): self.name = name self.career = career self.topic = topic def speak1(self): print(f'我叫{self.name},我是一个{self.career},我演讲的主题是{self.topic}') class Student(Speaker, People): pass s = Student(name='Jonh', age='30', career='演说家', topic='Python') s.speak() s.speak1()
正在回答
同学,你好,可以看下‘进击的蜂蜜’同学提供的思路,下边是正确代码。同学可以参考一下
class People(object): def __init__(self, name, age): self.name = name self.age = age def speak(self): print(f'{self.name}说: 我{self.age}岁') class Speaker(object): def __init__(self, name, career,topic): self.name = name self.career = career self.topic = topic def speak1(self): print(f'我叫{self.name},我是一个{self.career},我演讲的主题是{self.topic}') class Student(Speaker, People): def __init__(self,name,age,career,topic): People.__init__(self,name,age) Speaker.__init__(self,name,career,topic) pass s = Student(name='Jonh', age=30, career='演说家',topic='Python') s.speak() s.speak1()
class People(object):
def __init__(self, name, age):
self.name = name
self.age = age
def speak(self):
print(f'{self.name}说: 我{self.age}岁')
class Speaker(object):
def __init__(self, name, career,topic):
self.name = name
self.career = career
self.topic = topic
def speak1(self):
print(f'我叫{self.name},我是一个{self.career},我演讲的主题是{self.topic}')
class Student(Speaker, People):
def __init__(self,name,age,career,topic):
Speaker.__init__(self,name,age)
People.__init__(self,name,career,topic)
pass
s = Student(name='Jonh', age=30, career='演说家',topic='Python')
s.speak()
s.speak1()
同学,你好,同学是想要Poeple和Speaker两个类中的属性和方法都使用吗?如果是的需要用到继承,参考代码:
class People(object): def __init__(self, name, age): self.name = name self.age = age def speak(self): print(f'{self.name}说: 我{self.age}岁') # 继承People类 class Speaker(People): def __init__(self, name, age, career, topic): super().__init__(name, age) # self.name = name self.career = career self.topic = topic def speak1(self): super(Speaker, self).speak() print(f'我叫{self.name},我是一个{self.career},我演讲的主题是{self.topic}') class Student(Speaker): pass s = Student(name='Jonh', age='30', career='演说家', topic='Python') # s.speak() s.speak1()
同学可以看下是否是同学描述的意思,如果不是的话,同学可以更详细的描述一下同学的想法。
如果我的回答解决了您的疑惑,请采纳!祝学习愉快~~~~
- 参与学习 人
- 提交作业 2727 份
- 解答问题 8160 个
想要进入Python Web、爬虫、人工智能等高薪领域,你需要掌握本阶段的Python基础知识,课程安排带你高效学习轻松入门,学完你也能听得懂Python工程师的行业梗。
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星