How to dynamically compose and access class attributes in Python? [duplicate]

You can use getattr() to access a property when you don’t know its name until runtime:

obj = myobject()
i = 7
date7 = getattr(obj, 'date%d' % i) # same as obj.date7

If you keep your numbered classes in a module called foo, you can use getattr() again to access them by number.

foo.py:
  class Class1: pass
  class Class2: pass
  [ etc ]


bar.py:
  import foo
  i = 3
  someClass = getattr(foo, "Class%d" % i) # Same as someClass = foo.Class3
  obj = someClass() # someClass is a pointer to foo.Class3
  # short version:
  obj = getattr(foo, "Class%d" % i)()

Having said all that, you really should avoid this sort of thing because you will never be able to find out where these numbered properties and classes are being used except by reading through your entire codebase. You are better off putting everything in a dictionary.

Leave a Comment