Python类继承问题

mea*_*ade 16 python inheritance class

我正在使用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'
Run Code Online (Sandbox Code Playgroud)

这是代码

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()
Run Code Online (Sandbox Code Playgroud)

wor*_*ad3 25

三件事:

  1. 您需要显式调用构造函数.它不像C++那样自动调用
  2. 使用从object继承的新样式类
  3. 使用新式类,使用可用的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'
Run Code Online (Sandbox Code Playgroud)

建议使用super,因为它在多个继承情况下也只能正确处理调用构造函数一次(只要继承图中的每个类也使用super).这也是一个你需要的,如果/当你改变什么一类是继承自修改代码少的地方(例如,你分解出一个基类,改变推导,并不需要担心你的类调用了错误的父构造函数).同样在MI前端,您只需要一个超级调用来正确调用所有基类构造函数.

  • 使用超级时一定要小心,请阅读:http://fuhm.net/super-harmful/ (4认同)

Mar*_*ote 9

你应该明确地调用超类的init函数:

class Employee(Person):
    def __init__(self):
        Person.__init__(self)
        self.empnum = "abc123"
Run Code Online (Sandbox Code Playgroud)


wr.*_*wr. 5

Employee必须显式调用父级的__init__(不是init):

 class Employee(Person):  
    def __init__(self):  
         Person.__init__(self)  
         self.empnum = 'abc123'  
Run Code Online (Sandbox Code Playgroud)