简体   繁体   English

什么时候使用super(Baseclass,self).__ init__

[英]when is super(Baseclass, self).__init__ used

When should the following code be used in Python (Assume that Baseclass inherits from Parent class and Parent class has some variables initiated in __init__ () method) 何时应在Python中使用以下代码(假定Baseclass继承自Parent类,并且Parent类在__init__ ()方法中初始化了一些变量)

class Baseclass(Parent):
    def __init__(self, some_arg):
        self.some_arg = some_arg
        super(Baseclass, self).__init__()

Does this code makes all the local variables defined in __init__ method of Parent class accessible in Baseclass? 此代码是否可以在Baseclass中访问在Parent类的__init__方法中定义的所有局部变量? What significance does it make? 它有什么意义?

super keeps your code from being repetitive; super防止您的代码重复出现; a complex __init__ needn't be c/p'ed into your inheriting classes. 不需要将复杂的__init__放入继承的类中。 It also makes MRO work as it should, such that if you use multiple inheritance it will work correctly. 它还可以使MRO正常工作,因此,如果使用多重继承,它将可以正常工作。

One reason to do this would be to ensure that all of your inheriting objects have certain attributes which they don't have from the parent. 这样做的原因之一是要确保所有继承对象都具有某些父级不具备的属性。 If you simply write a new __init__ , they won't have them unless you repeat your code. 如果您只是简单地编写一个新的__init__ ,则除非重复您的代码,否则它们将没有它们。 For example: 例如:

>>> class A(object):
...     def __init__(self, x):
...             self.x = x
... 
>>> class B(A):
...     def __init__(self, y):
...             self.y = y
... 
>>> Stick = B(15)
>>> Stick.x
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'B' object has no attribute 'x'
>>>

Without calling super during the __init__ the entire method is simply overridden. 无需在__init__期间调用super ,整个方法将被简单地覆盖。 A call to super here ensures that both variables exist in the inherited class. 此处对super的调用可确保两个变量都存在于继承的类中。

>>> class C(A):
...     def __init__(self, x, y):
...             super(C, self).__init__(x)
...             self.y = y
... 
>>> Dave = C(15, 22)
>>> Dave.x
15
>>> Dave.y
22
>>>  

Note that in the super call, x is passed to the __init__() call, but self is taken care of in the super(C, self) part of the code. 请注意,在super调用中, x传递给__init__()调用,但是self在代码的super(C, self)部分中得到照顾。

EDIT: TyrantWave also rightly points out that super is also quite useful outside of __init__ . 编辑:TyrantWave也正确地指出,在__init__之外, super也非常有用。 Take an object with a simple foo method for example. 以带有简单foo方法的对象为例。

class Parent(object):
    def foo(self):
        return "I say foo!"

The inherited class may want to just alter the output of this function instead of totally rewriting it. 继承的类可能只想更改此函数的输出,而不是完全重写它。 So instead of repeating ourselves and writing the same code over again, we just call super to get the parent's return value, then work with the data and return the child class's modified results. 因此,我们无需重复自己并再次编写相同的代码,而只需调用super以获取父级的返回值,然后使用该数据并返回子级的修改后的结果。

class Child(Parent):
    def foo(self):
        parent_result = super(Child, self).foo()
        return "I'm a child!! %s" % parent_result

In the above, the call to super returns the Parent s value for foo() and then the Child goes on to work with the data further before returning it themselves. 在上面的代码中,对super的调用返回foo()Parent的值,然后Child继续进一步处理数据,然后再返回自身。

>>> Alan = Parent()
>>> Stan = Child()
>>> Alan.foo()
'I say foo!'
>>> Stan.foo()
"I'm a child!! I say foo!"
>>> 

暂无
暂无

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

相关问题 为什么在多次继承中执行Base .__ init __(self)而不是super().__ init __()时会跳过__init__? - Why is an __init__ skipped when doing Base.__init__(self) in multiple inheritance instead of super().__init__()? Python:super和__init __()vs __init __(self) - Python: super and __init__() vs __init__( self ) 为什么不在 Pytorch 中使用 super().__init__(Model,self) - Why not super().__init__(Model,self) in Pytorch “在__init__调用中使用self.tr时,从未调用%S的RuntimeError:超类__init __() - “RuntimeError: super-class __init__() of %S was never called” when using self.tr in __init__ call 在python中调用超类的__init__时,Self的显式传递 - Explicit passing of Self when calling super class's __init__ in python 什么时候调用 Python 的 super().__init__()? - When to call Python's super().__init__()? 使用子类和super时__init__的参数 - Arguments to __init__ when using a subclass and super 如何调用super(MyClass,self).__ init __()而不使用MyClass? - Way to call super(MyClass, self).__init__() without MyClass? 为什么在类没有指定超类时使用super().__ init __(* args,** kwargs)? - Why is super().__init__(*args,**kwargs) being used when class doesn't specify a superclass? 为什么 super(MainWindow, self),__init__(*args, **kwargs) NameError: name '__init__' is not defined - why does super(MainWindow, self),__init__(*args, **kwargs) NameError: name '__init__' is not defined
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM