Class attributes with a “calculated” name
-
06-09-2019 - |
Question
When defining class attributes through "calculated" names, as in:
class C(object):
for name in (....):
exec("%s = ..." % (name,...))
is there a different way of handling the numerous attribute definitions than by using an exec? getattr(C, name) does not work because C is not defined, during class construction...
Solution
How about:
class C(object):
blah blah
for name in (...):
setattr(C, name, "....")
That is, do the attribute setting after the definition.
OTHER TIPS
class C (object):
pass
c = C()
c.__dict__['foo'] = 42
c.foo # returns 42
If your entire class is "calculated", then may I suggest the type
callable. This is especially useful if your original container was a dict:
d = dict(('member-%d' % k, k*100) for k in range(10))
C = type('C', (), d)
This would give you the same results as
class C(object):
member-0 = 0
member-1 = 100
...
If your needs are really complex, consider metaclasses. (In fact, type
is a metaclass =)
What about using metaclasses for this purpose?
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow