2012-10-20 173 views
0

我正在試圖表示一個電子電路的項目。這個問題不涉及電路理論,僅僅涉及對象之間的連接。Python - 引用對象屬性

問題是我需要以兩種不同的方式在兩個對象之間建立連接。

我有一個組件和一個節點。一個組件有兩個終端(正面和負面),每個終端連接一個節點。節點可以有許多不同的終端連接到它。

所以,我可以有

component1.positive = node1

但是,如果我想也做

node1.add_terminal(component1.positive)

這將只是給節點1對自身的引用。

我希望能夠有節點包含其中的組件連接到它或引用它,其終端的集合,而無需編寫

node1.add_terminal(component1, "positive")

或類似的東西。

那麼,有沒有辦法存儲「component1.positive」,以便它可以追溯到組件和該組件的特定終端?或者還有另外一種方式來表達這種多對一和一對多的關係嗎?

編輯:

的Node對象可以知道哪些部件的兩端它連接到這一點很重要。

+0

它是一個選項,使節點的字典或列表? – Difusio

回答

1

您可以使用屬性。考慮這個(更新):

class Terminal(object) 
    def __init__(self, component, node = None): 
     self.component = component 
     self.node = node 

    def connect(self, node): 
     node.add_terminal(self) 
     self.node = node 

    def disconnect(self): 
     self.node.remove_terminal(self) 
     self.node = None  

class Component(object): 
    def __init__(self): 
     self._positive = Terminal(self) 

    @property 
    def positive(self): 
     return self._positive 

    @positive.setter 
    def positive(self, node): 
     self._positive.connect(node) 

    @positive.deleter 
    def positive(self): 
     self._positive.disconnect() 

用法:

c = Component() 
n = Node() 

c.positive = n # at this point c.positive.connect(n) thus 
       # n.add_terminal(c.positive) is called 
del c.positive # at this point positive is "disconnected" 
       # from the node and vise-versa. 
# or disconnect explicitly 
c.positive.disconnect() 
+0

這基本上是我第一次解決問題。問題是,節點不知道它連接到的組件的哪個終端。應該只有一個節點連接到終端,並且使用此代碼,至少可以引用相同組件的兩個節點,而不是組件終端。但是,我認爲在setter中調用節點對象的代碼非常乾淨。 –

+0

@KevinWard,在這種情況下,在Node.add_terminal(t)中檢查終端是否連接到另一個節點。我會在一分鐘內更新代碼。 –

+0

我已經更新了答案。看起來好多了:) –

0

總之,你不能。不存在對對象屬性的引用,只引用對象。你確實必須存儲一個對象的標識符,該標識符表示該對象中的存儲位置(不一定是屬性名稱的字符串,可以是成員字典的關鍵字或索引列入清單)。

但是,您不一定需要這些信息。以不同的方式對這些關係進行建模可能更有意義,並且/或者不會將對象本身的知識給予對象,而是將它們視爲圖並在該圖上執行遍歷。這會讓您瞭解每個參考的端點,而無需明確記錄它。