2015-12-22 68 views
0

我刚刚开始学习关于Python 3中的类和继承。我想要打印从超类Person继承的学生的名称。不幸的是我不断得到一个TypError。为什么使用super()时会出现类型错误?

代码:

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) 

但我不断收到此错误信息:

回溯(最近通话最后): TypeError:init()缺少2个必需的位置参数:'name'和'age'

+0

您没有给出init名称和年龄,就像您声明的那样。 '学生()'不会工作,因为你给它的参数,你现在没有调用它。 – pvg

回答

0

__init__()方法Student需要2位置参数:nameage。您需要指定这些参数创建新实例时:

student1 = Student('eppe2000', 20) 
print(student1.name) 

如果改为希望类Student默认为阶级Person默认参数,如果它们没有被指定,你可以做这样的:

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, university="University of Stockholm", gpa=8, **kwargs): 
     super().__init__(**kwargs) 
     self.university = university 
     self.gpa = gpa 


>>> s = Student() 
>>> s.name 
'Mike' 

>>> s = Student(name="Daniele") 
>>> s.name 
'Daniele' 

基本上,您将所有类Student未知的关键字参数转发给其父类。不是说如果你指定了一个无效的关键字(例如:'surname'),你将得到一个TypeError,因为StudentPerson都没有指定关键字参数和关键字'surname'。

如果您需要了解**kwargs检查这个职位信息:https://stackoverflow.com/a/36908/3477005

+0

谢谢。但我试图完成的是,每一个新的学生对象创建,继承了“名”和“时代”从Person”类,这是最初设置为‘迈克’,25 – eppe2000

0

如果你想Student总是默认的名字和父类的年龄,那么你不想Student取了个名字和年龄值。

class Student(Person): 
    def __init__(self, university = "University of Stockholm", gpa = 8): 
     super().__init__() # runs parent __init__ taking no values 
     self.university = university 
     self.gpa = gpa 

>>> student1 = Student() 
>>> student1.name 
'Mike' 
>>> student1.age 
25 

当您使用super().__init__(name, age)你是想传递给学生类的父类的名字和年龄。但是因为你不想传递任何东西,所以会出现错误。

现在,如果你想Student类能够采取值以及默认的,你可以做到这一点的父类中提供的那些。

class Student(Person): 
    def __init__(self, name = None, age = None, university = "University of Stockholm", gpa = 8): 
     if name is None and age is None: 
      super().__init__() 
     else: 
      super().__init__(name, age) 
     self.university = university 
     self.gpa = gpa 

这里会发生什么情况是,如果没有名字,年龄从Person类提供if name is None and age is None然后将其默认为值。但是如果这二者,姓名和年龄,然后它会使用这些值。

>>> student1 = Student() 
>>> student1.name 
'Mike' 
>>> student1.age 
25 
>>> student2 = Student('Bill', 19) 
>>> student2.name 
'Bill' 
>>> student2.age 
19 
+0

感谢你们为您的明确的解释和属性迅速回应! @DanielePantaleone – eppe2000

相关问题