python “Use of super on an old style class”的解决办法

来源:互联网 发布:数据库原理与应用 pdf 编辑:程序博客网 时间:2024/06/15 13:22

在调试代码时,发现引用的第三方架包突然提示如下错误:

E1002:<line,row>:Employee.__init__: Use of super on an old style class

仔细诊断代码,发现相关的内容如下:

class Base:    def __init__(self, username, age):        self.username = username        self.age = ageclass Employee(Base):    #   在这里提示错误,Use of super on an old style class    def __init__(self, username, age):        super(Employee, self).__init__(username, age)

强行运行,又提示如下错误:

File "e:/Python/mirana-python/ClassExtend.py", line 15, in __init__    super(Employee, self).__init__(self, username, age)    TypeError: super() argument 1 must be type, not classobj

查询相关资料,发现Python类的继承有两种写法,一是老样式(old style),一是新样式(new style),都能解决上述的错误。

1. 老写法(old style)

老写法不能使用super函数,必须通过类名进行调用,这样的问题就在于,出现多重继承时,应该说多层继承更为准确,A是基类,B继承A,C继承A,D继承B、C,这样在D被初始化时,就可能出现A的初始化函数被调用多次,写法如下:

#   old styleclass Base:    def __init__(self, username, age):        self.username = username        self.age = ageclass Employee(Base):    def __init__(self, username, age):        #   通过类名进行调用,必须携带self        Base.__init__(self, username, age)

2. 新写法(new style)

与老写法的区别在于,一是基类必须继承object,二是调用父类的方法时必须采用super方法,当然它也能解决老写法的重复调用问题,是现在面向对象编程的推荐写法,如下:

#   第一处差异,必须继承objectclass Base(object):    def __init__(self, username, age):        self.username = username        self.age = ageclass Employee(Base):    def __init__(self, username, age):        # 第二处差异,必须使用super函数,并且省略self参数        super(Employee, self).__init__(username, age)

结论

python面向对象编程实现继承有两种写法,一是老写法,二是新写法,明白了它们的差异,就能写出更高效、扩展性更强的代码。

阅读全文
0 0