开发者

How can I use Python's super() to update a parent value?

开发者 https://www.devze.com 2023-03-01 16:58 出处:网络
I\'m new to inheri开发者_C百科tance and all of the previous discussions about inheritance and Python\'s super() function are a bit over my head. I currently use the following code to update a parent o

I'm new to inheri开发者_C百科tance and all of the previous discussions about inheritance and Python's super() function are a bit over my head. I currently use the following code to update a parent object's value.

#!/usr/bin/env python
# test.py

class Master(object):
    mydata = []
    def __init__(self):
        s1 = Sub1(self)
        s2 = Sub2(self)

class Sub1(object):
    def __init__(self,p):
        self.p = p
        self.p.mydata.append(1)

class Sub2(object):
    def __init__(self,p):
        self.p = p
        self.p.mydata.append(2)

if __name__ == "__main__":
    m = Master()
    print m.mydata

This command line returns as follows:

user@host:~$ ./test.py

[1, 2]

Is there a better way to do this with super() instead of passing the the "self" reference to the child?


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:

class Master(object):
    mydata = None
    def __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.


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.py

class Master(object):
    mydata = []
    def __init__(self):
        s1 = Sub1()
        s2 = Sub2()

class Sub1(Master):
    def __init__(self):
        super(Sub1, self).mydata.append(1)

class Sub2(Master):
    def __init__(self):
        super(Sub2, self).mydata.append(2)

if __name__ == "__main__":
    m = Master()
    print m.mydata
0

精彩评论

暂无评论...
验证码 换一张
取 消