0

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?

pythonman
  • 3
  • 1
  • Possible duplicate: http://stackoverflow.com/questions/553784/can-you-use-a-string-to-instantiate-a-class-in-python – intelis Aug 21 '15 at 04:50

1 Answers1

3
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
demented hedgehog
  • 7,007
  • 4
  • 42
  • 49