python - 将参数传递给父类(super class)构造函数而不在子类构造函数中重复它们

标签 python oop

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 类构造函数参数,但是上面的代码没有' 似乎工作。执行此操作的正确方法是什么?

澄清:

这个想法是为了避免将父类的构造函数参数放在子类的构造函数中。只是重复太多了。我所有的父类和子类都有很多构造函数要接受的参数,因此一次又一次地重复它们不是很有效率,也很难维护。我正在尝试看看我是否可以只在其构造函数中定义子类的唯一性,但仍然初始化继承的属性。

最佳答案

在Python2中,你写

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

super 的第一个参数是子类,第二个参数是您希望作为其父类实例引用的对象的实例。

在 Python 3 中,super 拥有超能力,你可以写

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 语法实现该效果,例如:

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

关于python - 将参数传递给父类(super class)构造函数而不在子类构造函数中重复它们,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35262673/

相关文章:

php - PHP 中奇怪的魔法 __get() 行为

python - 将 python 模块从现有环境移动到 anaconda

python - Pyhook 事件。注入(inject)?

python - 使用 python 和 scikit-learn 的 DBSCAN : What exactly are the integer labes returned by make_blobs?

python - tf.gradients 和 tf.train.RMSPropOptimizer(lr_rate).compute_gradients 有什么区别?

python - 多态性或继承或任何其他建议?

c# - 设置DataGridView中的最大行数?

Perl 对象错误 : Can't locate object method via package

python - 最好使用的团队制作算法?

java - Java 中的抽象类初始化