[英]Access parents variables in Python
我有這樣的事情:
class SomeObject:
#code to access parents MyVar
class MyClass:
MyVar = 3
MyObject = SomeObject()
我需要從MyObject
內部訪問MyVar
。 有什么辦法可以做到嗎?
謝謝!
您可以將對MyClass對象的引用存儲在SomeObject中。 當使用MyClass Object作為參數構造函數時,可以初始化引用。
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)
您必須存儲對父母的引用,但是您可以使魔術自動發生:
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
,持有至參考a
。他們引用計數永遠不會變為0,所以它們不是垃圾回收)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.