如何使用Python的super()更新父值? [英] How can I use Python's super() to update a parent value?
问题描述
我是继承的新手,以前关于继承和Python的super()函数的所有讨论都让我有些头疼.我目前使用以下代码更新父对象的值.
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
此命令行返回如下:
user @ host:〜$ ./test.py
[1、2]
user@host:~$ ./test.py
[1, 2]
是否有更好的方法通过super()而不是将"self"引用传递给孩子?
Is there a better way to do this with super() instead of passing the the "self" reference to the child?
推荐答案
super
仅适用于类继承结构,其中Sub1
和Sub2
是Master
的子类.
super
only applies to class inheritance structures, where Sub1
and Sub2
are subclasses of Master
.
在您的示例中,您使用一个包含结构,Sub1
和Sub2
是Master
的属性,并且对super
调用没有用.
In your example, you use a containment structure, Sub1
and Sub2
are attributes of Master
, and you have no use for super
calls.
此外,您通常真的不想使用可变列表作为类属性;追加它会全局(而不是按实例)更改列表的一个副本(在类中定义);而是使用Master.__init__
方法初始化列表:
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 = []
调用__init__
函数来设置新实例,并通过在其中为self
分配新的空列表来确保每个实例都有自己的副本.
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.
这篇关于如何使用Python的super()更新父值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!