【问题标题】:Getting container/parent object from within python从 python 中获取容器/父对象
【发布时间】:2012-06-03 05:31:47
【问题描述】:

在 Python 中,是否可以从 Bar 自身中获取包含另一个对象 Bar 的对象,比如 Foo?这是我的意思的一个例子

class Foo(object):
    def __init__(self):
        self.bar = Bar()
        self.text = "Hello World"

class Bar(object):
    def __init__(self):
        self.newText = foo.text #This is what I want to do, 
                                #access the properties of the container object

foo = Foo()

这可能吗?谢谢!

【问题讨论】:

  • 你打错了;在Foo.__init__,self.bar = Foo() 应该是self.bar = Bar()。否则你有一个无限循环(为了创建一个 Foo,你首先必须创建一个 Foo)。

标签: python class object containers


【解决方案1】:

传递对 Bar 对象的引用,如下所示:

class Foo(object):
    def __init__(self):
        self.text = "Hello World"  # has to be created first, so Bar.__init__ can reference it
        self.bar = Bar(self)

class Bar(object):
    def __init__(self, parent):
        self.parent = parent
        self.newText = parent.text

foo = Foo()

编辑: 正如@thomleo 所指出的,这可能会导致垃圾收集出现问题。建议的解决方案位于http://eli.thegreenplace.net/2009/06/12/safely-using-destructors-in-python/,看起来像

import weakref

class Foo(object):
    def __init__(self):
        self.text = "Hello World"
        self.bar = Bar(self)

class Bar(object):
    def __init__(self, parent):
        self.parent = weakref.ref(parent)    # <= garbage-collector safe!
        self.newText = parent.text

foo = Foo()

【讨论】:

  • 谢谢,这行得通。我能看到的唯一问题是,当我尝试访问许多对象时,我将调用parent.parent.parent.etc。有没有更简洁的方法?
  • 如果我没记错的话,还有一个大问题。当您尝试执行 del foo 时,它不一定会破坏它,因为对它的引用仍然存在于 Bar 的 .parent 属性中,它包含...
  • @MichaelMcClenaghan,在这种情况下,您可以迭代多次而不是手动拼写出来。当然,这取决于结构...
  • 不需要调用弱引用对象吗? self.newText = self.parent().text
  • 我的错误,答案是使用 parent.text(对象)而不是 self.parent.text(弱引用)
【解决方案2】:

是否有可能从 Bar 自身中获取包含另一个对象 Bar 的对象,比如 Foo?

不是“自动”,因为语言不是这样构建的,特别是语言的构建使得无法保证 Foo 存在。

也就是说,您始终可以明确地执行此操作。属性,就像 Python 中的所有其他标识符一样,只是名称,而不是数据的存储空间;所以没有什么能阻止你让 Bar 实例有一个手动分配的 foo 属性,它是一个 Foo 实例,反之亦然。

【讨论】:

    【解决方案3】:

    是的,这是可能的。即使没有在对象创建时传递容器引用,即如果您的对象是类属性。 你的对象需要实现描述符协议(有一个__get__()):

    class ChildName(SimpleNamespace):                                                         
    
        def __get__(self, instance, owner):
            # instance is our parent
            return f'I am {self.name}, my parent is {instance.name}.'
    
    
    class ChildDiff(SimpleNamespace):
    
        @property
        def diff(self):
            return self.born - self.parent.born
    
        def age_diff(self):
            return f'I am {self.diff} years older than {self.parent.name}.'
    
        def __get__(self, instance, owner):
            self.parent = instance  # XXX: weakref?
            return self  # expose object to be able call age_diff() etc.
    
    
    class Parent(SimpleNamespace):
    
        child_name = ChildName(name='Bar')
        child_diff = ChildDiff(born=42)
    
    
    parent = Parent(name='Foo', born=23)
    print(parent.child_name)             # ... I am Bar, my parent is Foo.
    print(parent.child_diff.age_diff())  # ... I am 19 years older than Foo.
    

    【讨论】:

      【解决方案4】:

      这对我有用:

      父级:

      import child
      
      obj_1  = 25             # an object that both parent and child can access
      
      def startup():          # any startup function
          global obj_1
          child.ref( obj_1 )  # send the shared object to the child
          ...
      

      孩子:

      obj_1 = 0               # initual value will be overwritten
      
      def ref(shared_obj):    # receive a reference to the shared object
          global  obj_1       # shared object is global in the child, optional
          obj_1 = shared_obj  # set obj_1 in the child to be obj_1 in the parent
      

      【讨论】:

        【解决方案5】:

        如何使用继承:

        class Bar(object):
            def __init__(self):
                self.newText = self.text
        
        class Foo(Bar):
            def __init__(self):
                self.txt = 'Hello World'
                Bar.__init__(self)
        
        foo = Foo()
        print foo.newText
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-02-12
          • 2022-12-15
          • 2013-02-16
          • 2022-01-04
          • 1970-01-01
          • 1970-01-01
          • 2021-01-25
          相关资源
          最近更新 更多