在 Python 中访问父变量
我有这样的事情:
class SomeObject:
#code to access parents MyVar
class MyClass:
MyVar = 3
MyObject = SomeObject()
我需要从 MyObject
内部访问 MyVar
。我有什么办法可以做到这一点吗?
谢谢你!
I have something like this:
class SomeObject:
#code to access parents MyVar
class MyClass:
MyVar = 3
MyObject = SomeObject()
I need to access MyVar
from inside MyObject
. Is there any way I can do that?
Thank you!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以在 SomeObject 中存储对 MyClass 对象的引用。当您使用 MyClass 对象作为参数创建构造函数时,可以初始化该引用。
正如 unutbu 所说,我的代码没有运行,因此有一个更详细的示例。
You can store a reference to the MyClass object in the SomeObject. You can initialise the reference when you make an constructor with a MyClass Object as parameter.
As unutbu stated my code was not running, therefore a more detailed example.
您必须存储对父级的引用,但您可以使这种魔力自动发生:
通过覆盖 __setattr__ 和 __delattr__ 运算符,您可以控制子级对其父级的视图,并且确保连接始终正确。此外,这避免了使用笨拙的
add
/remove
方法;您可能会意外忘记使用的方法。这将您的对象限制为只有一个父对象,但对于这些类型的模型来说,这通常是可取的。最后,我建议您不要直接持有对父对象的引用,而是持有弱引用。这可以避免循环引用可能让垃圾收集器感到困惑(
a
保存对b
的引用,而b
保存对a
的引用它们的引用计数永远不会变为 0,因此它们不会被垃圾回收)。You have to store a reference to your parent, but you can make that magic happen automatically:
By overriding the
__setattr__
and__delattr__
operators you can control the child's view of its parent and make sure that the connection is always correct. Furthermore, this avoids using clumsyadd
/remove
methods; methods you may accidentally forget to use. This restricts your objects to having exactly one parent, but for these types of models, that is generally desirable.Lastly, I recommend that rather than holding a reference to the parent object directly, you hold a weak reference. This avoids cyclic references that may confuse the garbage collector (
a
holds a reference tob
, which holds a reference toa
. Their reference count never goes to 0, so they aren't garbage collected).