Python 如何从子类调用基类的 __init__ 方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19205916/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 13:08:42  来源:igfitidea点击:

How to call Base Class's __init__ method from the child class?

pythonpython-2.7inheritanceconstructor

提问by Prakhar Mohan Srivastava

If I have a python class as:

如果我有一个 python 类:

class BaseClass(object):
#code and the init function of the base class

And then I define a child class such as:

然后我定义了一个子类,例如:

class ChildClass(BaseClass):
#here I want to call the init function of the base class

If the init function of the base class takes some arguments that I am taking them as arguments of the child class's init function, how do I pass these arguments to the base class?

如果基类的 init 函数接受一些我将它们作为子类 init 函数的参数的参数,我该如何将这些参数传递给基类?

The code that I have written is:

我写的代码是:

class Car(object):
    condition = "new"

    def __init__(self, model, color, mpg):
        self.model = model
        self.color = color
        self.mpg   = mpg

class ElectricCar(Car):
    def __init__(self, battery_type, model, color, mpg):
        self.battery_type=battery_type
        super(ElectricCar, self).__init__(model, color, mpg)

Where am I going wrong?

我哪里错了?

采纳答案by Mingyu

You could use super(ChildClass, self).__init__()

你可以用 super(ChildClass, self).__init__()

class BaseClass(object):
    def __init__(self, *args, **kwargs):
        pass

class ChildClass(BaseClass):
    def __init__(self, *args, **kwargs):
        super(ChildClass, self).__init__(*args, **kwargs)

Your indentation is incorrect, here's the modified code:

您的缩进不正确,这是修改后的代码:

class Car(object):
    condition = "new"

    def __init__(self, model, color, mpg):
        self.model = model
        self.color = color
        self.mpg   = mpg

class ElectricCar(Car):
    def __init__(self, battery_type, model, color, mpg):
        self.battery_type=battery_type
        super(ElectricCar, self).__init__(model, color, mpg)

car = ElectricCar('battery', 'ford', 'golden', 10)
print car.__dict__

Here's the output:

这是输出:

{'color': 'golden', 'mpg': 10, 'model': 'ford', 'battery_type': 'battery'}

回答by thefourtheye

You can call the super class's constructor like this

您可以像这样调用超类的构造函数

class A(object):
    def __init__(self, number):
        print "parent", number

class B(A):
    def __init__(self):
        super(B, self).__init__(5)

b = B()

NOTE:

笔记:

This will work only when the parent class inherits object

这仅在父类继承时有效 object

回答by Manjunath Reddy

As Mingyu pointed out, there is a problem in formatting. Other than that, I would strongly recommend not using the Derived class's namewhile calling super()since it makes your code inflexible (code maintenance and inheritance issues). In Python 3, Use super().__init__instead. Here is the code after incorporating these changes :

正如明宇所指出的,格式有问题。除此之外,我强烈建议不要在调用时使用派生类的名称super()因为它会使您的代码不灵活(代码维护和继承问题)。在 Python 3 中,super().__init__改为使用。这是合并这些更改后的代码:

class Car(object):
    condition = "new"

    def __init__(self, model, color, mpg):
        self.model = model
        self.color = color
        self.mpg   = mpg

class ElectricCar(Car):

    def __init__(self, battery_type, model, color, mpg):
        self.battery_type=battery_type
        super().__init__(model, color, mpg)

Thanks to Erwin Mayer for pointing out the issue in using __class__with super()

感谢 Erwin Mayer 指出__class__与 super() 一起使用的问题

回答by Erwin Mayer

If you are using Python 3, it is recommended to simply call super() without any argument:

如果您使用的是 Python 3,建议只调用 super() 而不带任何参数:

class Car(object):
    condition = "new"

    def __init__(self, model, color, mpg):
        self.model = model
        self.color = color
        self.mpg   = mpg

class ElectricCar(Car):
    def __init__(self, battery_type, model, color, mpg):
        self.battery_type=battery_type
        super().__init__(model, color, mpg)

car = ElectricCar('battery', 'ford', 'golden', 10)
print car.__dict__

Do not call super with classas it may lead to infinite recursion exceptions as per this answer.

不要用class调用 super,因为根据这个答案,它可能会导致无限递归异常。