不能从超类继承
can’t inherit from superclass
我有一个像下面这样的简单代码,其中 class Employee 应该从 class Person 继承。
class Person:
def __init__(self, firstname, lastname, age):
self.firstname = firstname
self.lastname = lastname
self.age = age
def getname(self):
return self.firstname, self.lastname
def getage(self):
return self.age
class Employee(Person):
def __init__(self, first, last, empid, age):
Person.__init__(self, first, last, age):
self.empid = empid
def getemp(self):
return self.getname() + ", " + self.empid
employee = Employee("Bart", "Simpson", 1006, 16)
print(employee.getemp())
它给我这个错误:
File "/tmp/pyadv.py", line 156
Person.__init__(self, first, last, age):
^
SyntaxError: invalid syntax
我检查了 Python documentation about classes and it didn’t have that superclass initialization inside the __init__()
of the subclass. But I found that in other websites like here,其中 Dog 继承自 Pet。
那么,我错过了什么?
改变
Person.__init__(self, first, last, age):
至
super().__init__(first, last, age)
你没有遗漏任何东西。您需要去掉该行的 :
。
:
仅出现在原始定义之后,即:def getname(self):
,并且后面始终跟有声明函数的缩进行。当你调用一个函数时,你不会这样做。
我有一个像下面这样的简单代码,其中 class Employee 应该从 class Person 继承。
class Person:
def __init__(self, firstname, lastname, age):
self.firstname = firstname
self.lastname = lastname
self.age = age
def getname(self):
return self.firstname, self.lastname
def getage(self):
return self.age
class Employee(Person):
def __init__(self, first, last, empid, age):
Person.__init__(self, first, last, age):
self.empid = empid
def getemp(self):
return self.getname() + ", " + self.empid
employee = Employee("Bart", "Simpson", 1006, 16)
print(employee.getemp())
它给我这个错误:
File "/tmp/pyadv.py", line 156
Person.__init__(self, first, last, age):
^
SyntaxError: invalid syntax
我检查了 Python documentation about classes and it didn’t have that superclass initialization inside the __init__()
of the subclass. But I found that in other websites like here,其中 Dog 继承自 Pet。
那么,我错过了什么?
改变
Person.__init__(self, first, last, age):
至
super().__init__(first, last, age)
你没有遗漏任何东西。您需要去掉该行的 :
。
:
仅出现在原始定义之后,即:def getname(self):
,并且后面始终跟有声明函数的缩进行。当你调用一个函数时,你不会这样做。