Should __init__() call the parent class's __init__()?

后端 未结 7 1377
-上瘾入骨i
-上瘾入骨i 2020-12-02 07:07

I\'m used that in Objective-C I\'ve got this construct:

- (void)init {
    if (self = [super init]) {
        // init class
    }
    return self;
}
<         


        
7条回答
  •  萌比男神i
    2020-12-02 07:36

    Edit: (after the code change)
    There is no way for us to tell you whether you need or not to call your parent's __init__ (or any other function). Inheritance obviously would work without such call. It all depends on the logic of your code: for example, if all your __init__ is done in parent class, you can just skip child-class __init__ altogether.

    consider the following example:

    >>> class A:
        def __init__(self, val):
            self.a = val
    
    
    >>> class B(A):
        pass
    
    >>> class C(A):
        def __init__(self, val):
            A.__init__(self, val)
            self.a += val
    
    
    >>> A(4).a
    4
    >>> B(5).a
    5
    >>> C(6).a
    12
    

提交回复
热议问题