我正在創建兩個類,一個類需要保存另一個類的實例。但是我無法弄清楚如何正確初始化它。class Buttons:def __init__(self, number, scene): self.DICT = {} self.number = number self.DICT[number] = scenedef add_btn(self, number, scene): self.DICT[number] = sceneclass Switches:enclosure_name = ""gatewate_name = ""enclosure_id = 0switch_name = ""switch_location = ""switch_device_id = 0switch_mac = 0switch_termination = 0switch_group = 0Buttons buttons = Buttons()我計劃創建許多開關,每個開關有 2 到 6 個按鈕。每個按鈕都有一個數字和一個動作。如何將 Buttons 變量放入開關中?
1 回答
呼喚遠方
TA貢獻1856條經驗 獲得超11個贊
我對此的理解是每個Switch將包含一個Buttons對象,其中包含一個代表多個按鈕的字典。
的Switches類是多個交換機的表示:
簡單地給每個開關一個按鈕屬性:
class Switch:
def __init__(self):
self.switches = {}
def add_switch(self, number, buttons):
self.switches[number] = buttons
在Buttons對象中創建 switch pass 時:
switches = Switches(b)
b = Buttons(2, "scene")
switches.add_switch(10, b)
您仍然可以訪問開關的底層按鈕。例如向第 10 個開關添加按鈕:
switch.switches[10].add_btn(...)
如果你想要花哨,你可以實現 a__getitem__這樣你就可以switch直接索引。內部Switches:
def __getitem__(self, item):
return self.switches[item]
使用此方法您可以直接添加按鈕:
switch[10].add_btn(...)
添加回答
舉報
0/150
提交
取消
