Class Attributes with a Computed Name

When defining class attributes through "computed" names, as in:

class C(object):
    for name in (....):
        exec("%s = ..." % (name,...))

Is there a different way to handle multiple attribute definitions than using exec? getattr (C, name) does not work, because C is not defined during class construction ...

+3
source share
4 answers

What about:

class C(object):
    blah blah

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

That is, set the attribute after the definition.

+11
source
class C (object):
    pass

c = C()
c.__dict__['foo'] = 42
c.foo # returns 42
+3
source

"", type . , dict:

d = dict(('member-%d' % k, k*100) for k in range(10))
C = type('C', (), d)

,

class C(object):
    member-0 = 0
    member-1 = 100
    ...

, . (, type - =)

+2

How about using metaclasses for this purpose?

Check Question 100003: what is a metaclass in Python? .

0
source

Source: https://habr.com/ru/post/1709123/


All Articles