【发布时间】:2016-03-29 07:28:28
【问题描述】:
我刚开始学习 Python 3 中的类和继承。我想打印一个学生的名字,它是从超类 Person 继承的。不幸的是,我不断收到 TypError。
代码:
class Person(object):
def __init__(self, name="Mike", age = 25, place_of_birth="Stockholm"):
self.age = age
self.name = name
self.place_of_birth = place_of_birth
class Student(Person):
def __init__(self, name, age, university = "University of Stockholm", gpa = 8):
super().__init__(name, age)
self.university = university
self.gpa = gpa
然后我想通过调用来打印学生的姓名:
student1 = Student()
print(student1.name)
但我不断收到此错误消息:
Traceback(最近一次调用最后一次): TypeError: init() 缺少 2 个必需的位置参数:'name' 和 'age'
【问题讨论】:
-
您没有像您声明的那样给出初始化名称和年龄。
Student()不起作用,因为你给了它参数,而你现在没有调用它。
标签: python-3.x inheritance superclass super