我在玩Python类继承,遇到一个问题,即如果从子类(下面的代码)调用继承的__init__
,则从Active Python中得到的结果是:
>>> start
Tom Sneed
Sue Ann
Traceback (most recent call last):
File "C:\Python26\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", line 312, <br>in RunScript
exec codeObject in __main__.__dict__
File "C:\temp\classtest.py", line 22, in <module>
print y.get_emp()
File "C:\temp\classtest.py", line 16, in get_emp
return self.FirstName + ' ' + 'abc'
AttributeError: Employee instance has no attribute 'FirstName'
这是代码
class Person():
AnotherName = 'Sue Ann'
def __init__(self):
self.FirstName = 'Tom'
self.LastName = 'Sneed'
def get_name(self):
return self.FirstName + ' ' + self.LastName
class Employee(Person):
def __init__(self):
self.empnum = 'abc123'
def get_emp(self):
print self.AnotherName
return self.FirstName + ' ' + 'abc'
x = Person()
y = Employee()
print 'start'
print x.get_name()
print y.get_emp()
最佳答案
三件事:
您需要显式调用构造函数。它不会像C ++中那样自动为您调用
使用从对象继承的新型类
对于新样式的类,请使用可用的super()方法
看起来像:
class Person(object):
AnotherName = 'Sue Ann'
def __init__(self):
super(Person, self).__init__()
self.FirstName = 'Tom'
self.LastName = 'Sneed'
def get_name(self):
return self.FirstName + ' ' + self.LastName
class Employee(Person):
def __init__(self):
super(Employee, self).__init__()
self.empnum = 'abc123'
def get_emp(self):
print self.AnotherName
return self.FirstName + ' ' + 'abc'
建议使用super,因为它在多个继承的情况下也只能正确处理一次调用构造函数(只要继承图中的每个类也都使用super)。如果/当您更改继承自类的内容时(例如,您分解出一个基类并更改派生方式,并且不必担心您的类调用了错误的父类),这也是一个无需更改代码的地方构造函数)。同样在MI方面,您只需要一个超级调用即可正确调用所有基类构造函数。
关于python - Python类继承问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61514721/