Python类继承问题 [英] Python Class Inheritance issue

查看:257
本文介绍了Python类继承问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在玩Python类继承,并遇到一个问题,其中继承的 __ init __ 不执行,如果从子类(代码下面)调用结果我从活动Python获得的是:

I'm playing with Python Class inheritance and ran into a problem where the inherited __init__ is not being executed if called from the sub-class (code below) the result I get from Active Python is:

>>> 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'






< h2>以下代码


Here's the code

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()


推荐答案

三件事:


  1. 您需要显式调用构造函数。

  2. 使用从对象继承的新式类

  3. 对于新式类,请使用可以使用的超级()方法

这将是:

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前面,你只需要一个超级调用来正确地调用所有的基类构造函数。

Using super is recommended as it will also deal correctly with calling constructors only once in multiple inheritance cases (as long as each class in the inheritance graph also uses super). It's also one less place you need to change code if/when you change what a class is inherited from (for example, you factor out a base-class and change the derivation and don't need to worry about your classes calling the wrong parent constructors). Also on the MI front, you only need one super call to correctly call all the base-class constructors.

这篇关于Python类继承问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆