How Can I Use Python's Super() To Update A Parent Value?
Solution 1:
super
only applies to class inheritance structures, where Sub1
and Sub2
are subclasses of Master
.
In your example, you use a containment structure, Sub1
and Sub2
are attributes of Master
, and you have no use for super
calls.
Also, you generally really do not want to use a mutable list as a class attribute; appending to it will alter the one copy of the list (defined in the class) globally, not per instance; initiate the list in the Master.__init__
method instead:
classMaster(object):
mydata = Nonedef__init__(self):
self.mydata = []
The __init__
function is called to set up a new instance, and by assigning a new empty list to self
there, you ensure that each instance has it's own copy.
Solution 2:
Here's how you would do it by inheritance. You first have Master which is the parent class, then Sub1 and Sub2 will inherit from Master and become subclasses. All subclasses can access methods and variables in the parent class. This might be a duplicate of: Call a parent class's method from child class in Python?
#!/usr/bin/env python# test.pyclassMaster(object):
mydata = []
def__init__(self):
s1 = Sub1()
s2 = Sub2()
classSub1(Master):def__init__(self):
super(Sub1, self).mydata.append(1)
classSub2(Master):def__init__(self):
super(Sub2, self).mydata.append(2)
if __name__ == "__main__":
m = Master()
print m.mydata
Post a Comment for "How Can I Use Python's Super() To Update A Parent Value?"