如何使用 Python 的 super() 来更新父值?
我对继承很陌生,之前所有关于继承和 Python 的 super() 函数的讨论都有点超出我的理解。我当前使用以下代码来更新父对象的值。
#!/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
该命令行返回如下:
用户@主机:~$ ./test.py
[1, 2]
是否有更好的方法使用 super() 来执行此操作,而不是将“self”引用传递给子级?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
super
仅适用于类继承结构,其中Sub1
和Sub2
是Master
的子类。在您的示例中,您使用包含结构,
Sub1
和Sub2
是Master
的属性,并且您没有使用super< /code> 调用。
另外,您通常确实不想使用可变列表作为类属性;附加到它会全局更改列表的一份副本(在类中定义),而不是每个实例;相反,在
Master.__init__
方法中启动列表:调用
__init__
函数来设置新实例,并通过将新的空列表分配给self< /code> 在那里,您确保每个实例都有它自己的副本。
super
only applies to class inheritance structures, whereSub1
andSub2
are subclasses ofMaster
.In your example, you use a containment structure,
Sub1
andSub2
are attributes ofMaster
, and you have no use forsuper
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:The
__init__
function is called to set up a new instance, and by assigning a new empty list toself
there, you ensure that each instance has it's own copy.以下是通过继承来实现的方法。首先有Master,它是父类,然后Sub1和Sub2将继承Master并成为子类。所有子类都可以访问父类中的方法和变量。这可能与以下内容重复:调用Python 中子类的父类方法?
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?