2010-12-02 83 views
1
class A()  
    att = B()  

class B()  
    ... 

a = A() 

b = B() 

a.att = b 

b怎樣才能得到一個參考?我需要獲得這裏的屬性。Python - 如何從屬性類中獲取類實例引用?

謝謝!

+1

請閱讀[編輯幫助](http://stackoverflow.com/editing-help)並重新格式化您的文章。 – 2010-12-02 01:03:59

+0

att是A類的屬性還是類的實例? – martineau 2010-12-02 01:19:56

+0

att是A級的屬性。 非常感謝您的快速響應! – jeffrey 2010-12-02 01:53:07

回答

0

您可以製作一個通用的「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>]} 

最後,你必須從任何性能

反向引用的所有參考類
0

最簡單的方法是在B中需要A的方法中添加一個額外的函數參數,並在調用時傳遞它。或者,只是讓B的初始化拿一個A作爲參數,包括和改變的init將該位ATT = B(個體經營)

0
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 
0

此代碼沒有按沒有多大意義......但如果我正確理解你的問題......

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 

可能是一個答案。

0
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