在 Python 中访问父变量

发布于 2024-12-09 18:54:52 字数 240 浏览 0 评论 0原文

我有这样的事情:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

月光色 2024-12-16 18:54:52

您可以在 SomeObject 中存储对 MyClass 对象的引用。当您使用 MyClass 对象作为参数创建构造函数时,可以初始化该引用。

class SomeObject:
    def __init__(self, reference):
         self.reference_=reference
    #code to access parents MyVar
    self.reference_.MyVar=5

class MyClass:
    MyVar = 3

    MyObject = SomeObject(self)

正如 unutbu 所说,我的代码没有运行,因此有一个更详细的示例。

class SomeObject:
    def __init__(self):
         self.reference_=None

    def connect(self, reference):
        self.reference_=reference
    #code to access parents MyVar
    def call(self):
        self.reference_.MyVar=5

class MyClass:
    MyVar = 3
    MyObject = SomeObject()
    def connect(self):
        self.MyObject.connect(self)

if __name__ == '__main__':
    myclass = MyClass()
    myclass.connect()
    myclass.MyObject.call()
    print(myclass.MyVar)

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.

class SomeObject:
    def __init__(self, reference):
         self.reference_=reference
    #code to access parents MyVar
    self.reference_.MyVar=5

class MyClass:
    MyVar = 3

    MyObject = SomeObject(self)

As unutbu stated my code was not running, therefore a more detailed example.

class SomeObject:
    def __init__(self):
         self.reference_=None

    def connect(self, reference):
        self.reference_=reference
    #code to access parents MyVar
    def call(self):
        self.reference_.MyVar=5

class MyClass:
    MyVar = 3
    MyObject = SomeObject()
    def connect(self):
        self.MyObject.connect(self)

if __name__ == '__main__':
    myclass = MyClass()
    myclass.connect()
    myclass.MyObject.call()
    print(myclass.MyVar)
っ左 2024-12-16 18:54:52

您必须存储对父级的引用,但您可以使这种魔力自动发生:

from weakref import ref

class MyClass(object):
    def __setattr__(self, key, value):
        self.__dict__[key] = value
        try:
            value._parent = ref(self)
        except AttributeError:
            raise TypeError('MyClass cannot have children of type ' +
                            type(value).__name__)
    def __delattr__(self, key):
        v = self.__dict__[key]
        del self.__dict__[key]
        try:
            v._parent = None
        except AttributeError:
            raise TypeError('Child of MyClass is mysteriously '
                            'missing its parent')

class SomeObject(object):
    _parent = None
    @property
    def parent(self):
        if self._parent is not None:
            return self._parent()
        return None

>>> a = MyClass()
>>> a.b = SomeObject()
>>> print a.b.parent
<__main__.MyClass at 0x8ce60f0>
>>> b = a.b
>>> del a.b
>>> print b.parent
None

通过覆盖 __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:

from weakref import ref

class MyClass(object):
    def __setattr__(self, key, value):
        self.__dict__[key] = value
        try:
            value._parent = ref(self)
        except AttributeError:
            raise TypeError('MyClass cannot have children of type ' +
                            type(value).__name__)
    def __delattr__(self, key):
        v = self.__dict__[key]
        del self.__dict__[key]
        try:
            v._parent = None
        except AttributeError:
            raise TypeError('Child of MyClass is mysteriously '
                            'missing its parent')

class SomeObject(object):
    _parent = None
    @property
    def parent(self):
        if self._parent is not None:
            return self._parent()
        return None

>>> a = MyClass()
>>> a.b = SomeObject()
>>> print a.b.parent
<__main__.MyClass at 0x8ce60f0>
>>> b = a.b
>>> del a.b
>>> print b.parent
None

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 clumsy add/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 to b, which holds a reference to a. Their reference count never goes to 0, so they aren't garbage collected).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文