Passing arguments to superclass constructor withou

2019-03-25 09:05发布

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

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?

Clarification:

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.

标签: python oop
2条回答
【Aperson】
2楼-- · 2019-03-25 09:11

You can call parent class constructor by passing self and required arguments

class C(P):
    def __init__(self, a,b,c):
       P.__init__(self,a,b)
       self.c = c
查看更多
相关推荐>>
3楼-- · 2019-03-25 09:24

In Python2, you write

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

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.

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

Demo:

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

Response to your comment:

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

or

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
查看更多
登录 后发表回答