[英]Python Class as Class variable
I am creating two classes, one which needs to hold an instance of the other. 我正在创建两个类,一个需要保存另一个实例。 However I can not figure out how to properly initialize this.
但是我不知道如何正确初始化它。
class Buttons:
def __init__(self, number, scene):
self.DICT = {}
self.number = number
self.DICT[number] = scene
def add_btn(self, number, scene):
self.DICT[number] = scene
class Switches:
enclosure_name = ""
gatewate_name = ""
enclosure_id = 0
switch_name = ""
switch_location = ""
switch_device_id = 0
switch_mac = 0
switch_termination = 0
switch_group = 0
Buttons buttons = Buttons()
I plan to create many switches, each switch has 2 to 6 buttons. 我计划创建许多开关,每个开关有2到6个按钮。 Each button has a number and an action.
每个按钮都有一个数字和一个动作。 How can I put a Buttons variable into the switches?
如何将Buttons变量放入开关中?
My understanding of this is that each Switch
will contain one Buttons
object, which contains a dictionary that represents multiple buttons. 我的理解是,每个
Switch
将包含一个Buttons
对象,该对象包含代表多个按钮的字典。
The Switches
class is a representation of multiple switches: Switches
类表示多个开关:
Simply give each switch a buttons attribute: 只需给每个开关一个按钮属性:
class Switch:
def __init__(self):
self.switches = {}
def add_switch(self, number, buttons):
self.switches[number] = buttons
And when creating a switch pass in a Buttons
object: 并且在
Buttons
对象中创建开关传递时:
switches = Switches(b)
b = Buttons(2, "scene")
switches.add_switch(10, b)
And you can still access the underlying buttons of a switch. 而且您仍然可以访问开关的基础按钮。 For example adding buttons to the 10th switch:
例如,将按钮添加到第十个开关:
switch.switches[10].add_btn(...)
And if you want to be fancy you can implement a __getitem__
so you can index switch
directly. 如果您想花哨的话,可以实现
__getitem__
以便直接进行索引switch
。 Inside Switches
: 内部
Switches
:
def __getitem__(self, item):
return self.switches[item]
With this method you can add buttons directly: 使用这种方法,您可以直接添加按钮:
switch[10].add_btn(...)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.