Python类继承问题

2024-05-09 06:45:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我在玩Python类继承,遇到了一个问题,如果从子类(下面的代码)调用继承的__init__将不会执行,从活动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()

Tags: inpyselfgetreturninitdefline
3条回答

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

class Employee(Person):
    def __init__(self):
        Person.__init__(self)
        self.empnum = "abc123"

雇员必须显式调用父级的初始化(而不是初始化):

 class Employee(Person):  
    def __init__(self):  
         Person.__init__(self)  
         self.empnum = 'abc123'  

三件事:

  1. 您需要显式调用构造函数。它不是自动调用的,如C++ < /LI>
  2. 使用从对象继承的新样式类
  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'

建议使用super,因为它还可以在多个继承情况下(只要继承图中的每个类也使用super)只正确地处理一次调用构造函数。如果/当您更改继承自类的内容时(例如,您将基类分解出来并更改派生,而不必担心您的类调用了错误的父构造函数),您还需要在这里少修改代码。同样在MI前端,只需要一个超级调用就可以正确调用所有基类构造函数。

相关问题 更多 >