继承类中的python __init__方法 [英] python __init__ method in inherited class

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

问题描述

我想给一个子类一些额外的属性,而不必显式调用一个新方法。那么有一种方法可以为继承的类提供一个 __ init __ 类型方法,该方法不会覆盖父元素的 __ init __ 方法class?

I would like to give a daughter class some extra attributes without having to explicitly call a new method. So is there a way of giving the inherited class an __init__ type method which does not override the __init__ method of the parent class?

我编写下面的代码纯粹是为了说明我的问题(因此属性的命名很差等)。

I have written the code below purely to illustrate my question (hence the poor naming of attributes etc).

class initialclass():
    def __init__(self):
        self.attr1 = 'one'
        self.attr2 = 'two'    

class inheritedclass(initialclass):
    def __new__(self):
        self.attr3 = 'three'

    def somemethod(self):
        print 'the method'


a = inheritedclass()

for each in a.__dict__:
    print each

#I would like the output to be:
attr1
attr2
attr3

谢谢

推荐答案

据我所知,这是不可能的,但是你可以调用init的方法超类,像这样:

As far as I know that's not possible, however you can call the init method of the superclass, like this:

class inheritedclass(initialclass):
    def __init__(self):
        initialclass.__init__(self)
        self.attr3 = 'three'

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

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