[英]Python - how to get class instance reference from an attribute class?
class A()
att = B()
class B()
...
a = A()
b = B()
a.att = b
b如何获得a的引用? 我需要在这里获取a的属性。
谢谢!
最简单的方法是向需要A的B中的方法添加一个额外的函数参数,并在调用时将其传递给它。 或者,仅使B的init以A作为参数,然后将A的init的位更改为att = B(self)
class A(object):
def __init__(self):
self.att = B(self)
class B(object):
def __init__(self, a):
self.a = a
a = A()
a.att.a is a
或者另一种方式
class A(object):
def __init__(self, b):
b.a = self
self.att = b
class B(object):
pass
a = A(B())
a.att.a is a
这段代码没有什么意义...但是如果我正确理解了您的问题...
class A(object):
pass #or whatever you like
class B(object):
def __init__(self, ref): #accept one argument
self.ref = ref
a = A()
b = B(a) #pass `a` as that argument
a.att = b
可能是一个答案。
class A(object):
def __init__(self):
self._att=None
@property
def att(self):
return self._att
@att.setter
def att(self, value):
self._att = value
value.parent = self
class B(object):
pass
a = A()
b = B()
a.att = b
print b.parent
您可以创建一个通用的“ Reference()”类,该类将自身的任何引用保留在属性字典中。
class Reference(object):
def __init__(self):
self.references = {}
def __setattr__(self, key, value):
if hasattr(self, 'references'):
if isinstance(value, Reference):
if not key in value.references:
value.references[key] = []
value.references[key].append(self)
elif value is None and hasattr(self, key):
old = getattr(self, key).references
if key in old and self in old[key]:
old[key].remove(self)
super(Reference, self).__setattr__(key, value)
然后,创建您的类:
class A(Reference):
def __init__(self):
super(A, self).__init__()
self.att = None
class B(Reference):
def __init__(self):
super(B, self).__init__()
self.att = None
并使用它:
a = A()
b = B()
print 'A references', a.references
print 'B references', b.references
# A references {}
# B references {}
a.att = b
print 'A references', a.references
print 'B references', b.references
# A references {}
# B references {'att': [<__main__.A object at 0x7f731c8fc910>]}
最后,您将从任何属性中反向引用所有Reference类
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.