简体   繁体   English

扩展Python类的init方法

[英]Extend Python class's init method

I have a BaseClass and an AbstractClass that inherits from the BaseClass . 我有一个BaseClass和一个从BaseClass继承的AbstractClass This is the structure I have in place 这是我所拥有的结构

class BaseClass(object):
    def __init__(self, initialize=True):
        self.name = 'base_class'
        self.start = 0
        if initialize:
            self.start = 100

class AbstractClass(BaseClass):
    def __init__(self):
        self.name = 'asbtract_class'
        super(BaseClass, self).__init__()

I want to pass the abstract class an initialize parameter that gets transferred to the base class and if True sets the object's start value to 100 . 我想通过抽象类的initialize是被转移到基类的参数,如果True设置对象的start100

I tried using the super(BaseClass, self).__init__() but the abstract class gets no start attribute. 我尝试使用super(BaseClass, self).__init__()但是抽象类没有start属性。 I get an error when I try to access it. 尝试访问它时出现错误。

How can I pass a value the initialize argument to the AbstractClass and use the BaseClass 's __init__ method to set the start attribute on the AbstractClass . 我如何将initialize参数的值传递给AbstractClass并使用BaseClass__init__方法设置AbstractClassstart属性。

The code I used 我使用的代码

best = BaseClass()
abs = AbstractClass()
abs.start # AttributeError: 'AbstractClass' object has no attribute 'start'

To invoke the constructor of the super class you should use the class name of the sub class and not the super class, ie: 要调用超类的构造函数,您应该使用子类的类名而不是超类,即:

class AbstractClass(BaseClass):
    def __init__(self):
        super(AbstractClass, self).__init__()
        self.name = 'abstract_class'

Note also that I changed the order of invoking the constructor of the super class and setting the name attribute. 还要注意,我更改了调用超类的构造函数和设置name属性的顺序。 If you set it before calling the super, the attribute would be overridden by the constructor of the super class, which is most likely not what you intended 如果在调用super之前进行设置,则该属性将被super类的构造函数覆盖,这很可能不是您想要的

And as @Sraw pointed out, for python 3 the notation of calling the super no longer requires the referencing of the class name and can be simplified to 正如@Sraw所指出的,对于python 3,调用super的表示不再需要引用类名,并且可以简化为

class AbstractClass(BaseClass):
    def __init__(self):
        super().__init__()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM