继承类中的Python __init__方法



我想给子类一些额外的属性,而不必显式调用新方法。所以有没有一种方法给继承类一个__init__类型的方法,不覆盖父类的__init__方法?

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

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方法,像这样:

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

使用super调用父方的__init__:

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

我强烈建议遵循Python的命名约定,并以大写字母开始一个类,例如InheritedClassInitialClass

首先你把__init____new__混在一起,它们是不同的东西。__new__不接受instance (self)作为参数,它接受class (cls)。至于你问题的主要部分,你要做的是使用super来调用超类__init__

你的代码应该是这样的:

class initialclass(object):
    def __init__(self):
        self.attr1 = 'one'
        self.attr2 = 'two'    
class inheritedclass(initialclass):
    def __init__(self):
        self.attr3 = 'three'
        super(inheritedclass, self).__init__()

这非常简单。定义一个新的__init__方法,并在开始时调用父方法的__init__

# assuming a class Base, its __init__ takes one parameter x
class Derived(Base):
    def __init__(self, x, y):
        # whatever initialization is needed so we can say Derived is-a Base
        super(Derived, self).__init__(x)
        # now, add whatever makes Derived special - do your own initialization
        self.y = y

在Python 3中,您不必(因此为了简单起见可能不应该)显式地继承object或将类和self传递给super

从父类的init中调用指定的方法,如果它存在:

class initialclass():
    def __init__(self):
        self.attr1 = 'one'
        self.attr2 = 'two'  
        if hasattr(self, 'init_subclass'):
            self.init_subclass()
class inheritedclass(initialclass):
    def init_subclass(self):
        self.attr3 = 'three'
class initialclass:
        def __init__(self):
                self.attr1 = 'one'
                self.attr2 = 'two'
class inheritedclass(initialclass):
        def __init__(self):
                super().__init__()
                self.attr3 = 'three'
        def somemethod(self):
                print (self.attr1, self.attr2, self.attr3)
a=inheritedclass()
a.somemethod()
 1. List item

相关内容

  • 没有找到相关文章

最新更新