Python Forum

Full Version: Accessing subclass with a variable
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi All,

I'm new on this forum and pretty new in python. So maybe, my question will be quickly answered Big Grin

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
import device

class_types = {"rt": device.Router, "sw": device.Switch}
type_strings = ('sw', 'rt', 'sw')
hostname = 'test'
for type_string in type_strings:
    print(
        f'I will create an object type ## {class_types[type_string]} ## with this hostname : {hostname}')
    dv_obj = class_types[type_string](hostname)
    print(dv_obj)
Output:
I will create an object type ## <class '__main__.Switch'> ## with this hostname : test <__main__.Switch object at 0x00000208DB7DE088> I will create an object type ## <class '__main__.Router'> ## with this hostname : test <__main__.Router object at 0x00000208DB7DE048> I will create an object type ## <class '__main__.Switch'> ## with this hostname : test <__main__.Switch object at 0x00000208DB7DE088>
Many thanks for your help :)
it works fine :)