将参数传递给超类构造函数,而不必在子类构造函数中重复 [英] Passing arguments to superclass constructor without repeating them in childclass constructor

查看:92
本文介绍了将参数传递给超类构造函数,而不必在子类构造函数中重复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class P(object):
    def __init__(self, a, b):
       self.a = a
       self.b = b
class C(P):
    def __init__(self, c):
       P.__init__()
       self.c = c

obj = C(a, b, c) #want to instantiate a C with something like this

我想定义C类对象而不重写C的构造函数中的所有P类构造函数参数,但是上面的代码似乎不起作用.正确的做法是什么?

I want to define C class object without rewriting all the P class constructor argument in C's constructor, but the above code doesn't seem to work. What is the right approach to do this?

说明:

该想法是避免将父类的构造函数参数放在子类的构造函数中.只是重复太多了.我所有的父类和子类都有许多构造函数要接受的参数,因此一次又一次地重复它们并不是很有效并且很难维护.我试图查看是否只能在其构造函数中为子类定义唯一的东西,但仍初始化继承的属性.

The idea is to avoid putting parent class's constructor arguments in child class's constructor. It's just repeating too much. All my parent and child classes have many arguments to take in for constructors, so repeating them again and again is not very productive and difficult to maintain. I'm trying to see if I can only define what's unique for the child class in its constructor, but still initialize inherited attributes.

推荐答案

在Python2中,您编写

In Python2, you write

class C(P):
    def __init__(self, a, b, c):
        super(C, self).__init__(a, b)
        self.c = c

其中super的第一个参数是子类,第二个参数是您要引用作为其父类实例的对象的实例.

where the first argument to super is the child class and the second argument is the instance of the object which you want to have a reference to as an instance of its parent class.

在Python 3中,super具有超能力,您可以编写

In Python 3, super has superpowers and you can write

class C(P):
    def __init__(self, a, b, c):
        super().__init__(a, b)
        self.c = c

演示:

obj = C(1, 2, 3) 
print(obj.a, obj.b, obj.c) # 1 2 3

回复您的评论

您可以使用* args或** kwargs语法实现该效果,例如:

You could achieve that effect with the *args or **kwargs syntax, for example:

class C(P):
    def __init__(self, c, *args):
        super(C, self).__init__(*args)
        self.c = c

obj = C(3, 1, 2)
print(obj.a, obj.b, obj.c) # 1 2 3

class C(P):
    def __init__(self, c, **kwargs):
        super(C, self).__init__(**kwargs)
        self.c = c

obj = C(3, a=1, b=2)
print(obj.a, obj.b, obj.c) # 1 2 3

obj = C(a=1, b=2, c=3)
print(obj.a, obj.b, obj.c) # 1 2 3

这篇关于将参数传递给超类构造函数,而不必在子类构造函数中重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆