[英]Proper way to call the instance attribute of the parent class using super in python
我有以下代码,试图更好地理解super
在 python 中的工作原理
class Person:
species = "human"
def __init__(self, name, age):
self.name = name
self.age = age
def sing(self, song):
return "{} wants to sing the {} song".format(self.name, song)
class Student(Person):
def __init__(self, name, age, mark):
self.mark = mark
super(Student, self).__init__(name, age, mark)
student = Student(24, 8, "Ema")
此代码因错误而崩溃:
Traceback (most recent call last):
File "main.py", line 23, in <module>
student = Student(24, 8, "Ema")
File "main.py", line 17, in __init__
super(Student, self).__init__(name, age, mark)
TypeError: __init__() takes 3 positional arguments but 4 were given
我正在尝试使用父 class 的实例属性创建一个 object 学生,我到底做错了什么?
一个很好的解决方案作为例子:
class Person:
species = "human"
def __init__(self, name, age):
self.name = name
self.age = age
def sing(self, song):
return "{} will sing: {}".format(self.name, song)
class Profession(Person):
def __init__(self, title, company, name, age): # HERE
super().__init__(name, age) # HERE
self.title = title
self.company = company
person = Person("James", 12)
print(person.__class__.species)
print(person.name)
print(person.sing("Tomorrow never die"))
profession = Profession("President", "Rathor Inc.", "Ema", 43)
print(profession.name)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.