May-19-2020, 04:12 PM
Hi All,
I'm new on this forum and pretty new in python. So maybe, my question will be quickly answered
I'm currently trying to access a subclass with a variable.
I created a python module for class definition
module : device.py
But, as i advance with my code, i would know if it is possible to create an object (for example a Switch) depending on a variable to create the right object.
I tried this :
Am i crazy ? or dos it exist a solution to do this ?
Many thanks for your help !! :)
David
I'm new on this forum and pretty new in python. So maybe, my question will be quickly answered
I'm currently trying to access a subclass with a variable.
I created a python module for class definition
module : device.py
class Device:
def __init__(self, hostname):
self.hostname = hostname
self.description = None
class Router(Device):
def __init__(self, hostname):
super().__init__(hostname)
class Switch(Device):
def __init__(self, hostname):
super().__init__(hostname)I created one class Device, and a set of subclass to inherit from the Device class. I can create objects type Router or Switch without problem.But, as i advance with my code, i would know if it is possible to create an object (for example a Switch) depending on a variable to create the right object.
I tried this :
import device
classtype = {"rt":"Router","sw":"Switch"}
a = 'sw'
hostname = 'test'
for x in classtype:
if x == a:
print(f'I will create an object type ## {classtype[x]} ## with this hostname : {hostname}')
dv_obj = device.classtype[x](hostname)As you could see, my idea was to create the object depending on the value of "a" to avoid creating multiple if statement.Am i crazy ? or dos it exist a solution to do this ?
Many thanks for your help !! :)
David
