Reputation: 844
Suppose I have a class:
class Base:
def __init__(self, t1, t2, t3, t4, t5, ...):
self.t1 = t1
self.t2 = t2
self.t3 = t3
self.t4 = t4
self.t5 = t5
...
class Derived(Base):
def __init__(self, arg1, arg2, arg3, base_obj):
super(Derived, self).__init__(t1 = base_obj.t1, t2 = base_obj.t2, t3 = base_obj.t3, ...)
self.arg1 = arg1
self.arg2 = arg2
self.arg3 = arg3
base_obj1 = Base(1,2,3,4,5,...)
derived_obj1 = Derived('arg1', 'arg2', 'arg3', base_obj1)
As you can see Base
has a lots of attributes and I inherit them in the Derived
one-by-one which is very difficult to do, is there a way like I can just do something like this
super(Derived, self).__init__(self = base_obj)
So I don't have to inherit every attribute of Base
in Derived
manually
Upvotes: 1
Views: 69
Reputation: 39414
I would suggest that the Base
class have a method which picks the right attributes for you:
class Base:
def __init__(self, t1, t2, t3, t4, t5, ...):
self.t1 = t1
self.t2 = t2
self.t3 = t3
self.t4 = t4
self.t5 = t5
...
#Base should know which attributes are created in __init__()
#so this method just has to be kept in sync
def pick_init_attributes(self):
return (self.t1, self.t2, self.t3, ...)
class Derived(Base):
def __init__(self, arg1, arg2, arg3, base_obj):
super().__init__(*base_obj.pick_init_attributes())
self.arg1 = arg1
self.arg2 = arg2
self.arg3 = arg3
base_obj1 = Base(1,2,3,4,5,...)
derived_obj1 = Derived('arg1', 'arg2', 'arg3', base_obj1)
Also, when it comes time to write: class Derived2(Base):
you only need to copy/paste the super()...
line without needing to check whether it has the right attributes.
Upvotes: 3