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

人走茶凉 提交于 2019-12-10 21:39:30

问题


I'm new to inheritance 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?


回答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:

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.




回答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.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


来源:https://stackoverflow.com/questions/5849113/how-can-i-use-pythons-super-to-update-a-parent-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!