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. Each button has a number and an action. How can I put a Buttons variable into the switches?
My understanding of this is that each Switch
will contain one Buttons
object, which contains a dictionary that represents multiple buttons.
The Switches
class is a representation of multiple 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:
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. Inside Switches
:
def __getitem__(self, item):
return self.switches[item]
With this method you can add buttons directly:
switch[10].add_btn(...)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.