views:

116

answers:

4

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...

+11  A: 

How about:

class C(object):
    blah blah

for name in (...):
    setattr(C, name, "....")

That is, do the attribute setting after the definition.

Ned Batchelder
A: 

What about using metaclasses for this purpose?

Check out Question 100003 : What is a metaclass in Python?.

Mike Hordecki
+3  A: 
class C (object):
    pass

c = C()
c.__dict__['foo'] = 42
c.foo # returns 42
Dan
Ned's answer is better :)
Dan
+1 for your fair play, Dan. :)
EOL
+2  A: 

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 =)

Antti Rasinen