python - Passing arguments to superclass constructor without repeating them in childclass constructor -


class p(object):     def __init__(self, a, b):        self.a =        self.b = b class c(p):     def __init__(self, c):        p.__init__()        self.c = c  obj = c(a, b, c) #want instantiate c 

i want define c class object without rewriting p class constructor argument in c's constructor, above code doesn't seem work. right approach this?

clarification:

the idea avoid putting parent class's constructor arguments in child class's constructor. it's repeating much. parent , child classes have many arguments take in constructors, repeating them again , again not productive , difficult maintain. i'm trying see if can define what's unique child class in constructor, still initialize inherited attributes.

in python2, write

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

where first argument super child class , second argument instance of object want have reference instance of parent class.

in python 3, super has superpowers , 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 comment:

you achieve effect *args or **kwargs syntax, 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 

Comments

Popular posts from this blog

javascript - jQuery: Add class depending on URL in the best way -

caching - How to check if a url path exists in the service worker cache -

Redirect to a HTTPS version using .htaccess -