|
发表于 2024-2-1 16:16:59
|
显示全部楼层
本帖最后由 zhangchenyvn 于 2024-2-1 16:33 编辑
正确用法
这里,把改成直接init就可以了~
- class People:
- name = ''
- age = 0
- __weight = 0
-
- def __init__(self,n,a,w):
- self.name = n
- self.age = a
- self.__weight = w
-
- def speak(self):
- print("%s said: I am %d years old." %(self.name,self.age))
-
- class Student(People):
-
- def __init__(self,n,a,w,g):
- People.__init__(self,n,a,w)
- self.grade = g #一个更改
-
- def speak(self):
- print("%s said:I am %d years old and I am in Grade%d." %(self.name,self.age,self.grade))
- class Speaker:
- topic = ''
- name = ''
-
- def __init__(self,n,t):
- self.name = n
- self.topic = t
-
- def speak(self):
- print("I am %s.I am a speaker and my topic is %s" %(self.name,self.topic))
- class Sample01(Speaker, Student):
- def __init__(self, n, a, w, g, t):
- Student.__init__(self, n, a, w, g) # 显式调用 Student 的构造函数
- Speaker.__init__(self, n, t) # 显式调用 Speaker 的构造函数
- test = Sample01('Tim', 25, 80, 4, 'Python')
- test.speak() # 这将调用 Speaker 的 speak 方法,因为 Speaker 在继承顺序中排在前面
复制代码
由于先init了student类,后init了speaker类,因此speaker类的speak方法就覆盖了student类的speak方法,因此,输出了
|
|