I have a variable
class_name = "BigClass"
i need to access Class BigClass
static members like this BigClass.static_data
can i somehow convert the string inside variable class_name
into an actual class and access its static members in Python?
I have a variable
class_name = "BigClass"
i need to access Class BigClass
static members like this BigClass.static_data
can i somehow convert the string inside variable class_name
into an actual class and access its static members in Python?
class BigClass:
static_data = 42
def foo(self):
return "frog"
bc = eval("BigClass" + "()")
print bc.foo()
print bc.static_data
If you just want to access the static data then you can drop the "()" from the eval call.
Another approach is to use a class decorator to register the class in a lookup table (dictionary) and provide a lookup_class function. I like the second approach better, eval can be dangerous.
_cls_lookup = {}
def register_cls(cls):
_cls_lookup[cls.__name__] = cls
return cls
def lookup_cls(cls_name):
return _cls_lookup[cls_name]
@register_cls
class BigClass:
static_data = 42
bc = lookup_cls("BigClass")
print bc.static_data