Adding class attributes using a for loop in Python
suppose you want to dynamically add class attributes such as these
classDict = {}
for i in range(2):
classDict["func%s"%(i+1)] = lambda self:"X"
you can do this in several ways e.g. just add attributes after class has been created because you can'y easily access class name inside class
class Attr2(object):
pass
for n,v in classDict.iteritems():
setattr(Attr2, n, v)
print Attr2().func1(), Attr2().func2()
or better just create class on the fly e.g.
Attr3 = type("Attr3",(), classDict)
print Attr3().func1(), Attr3().func2()
or if you wish use metaclass e.g
class AttrMeta(type):
def __new__(cls, name, bases, dct):
dct.update(classDict)
return type.__new__(cls, name, bases, dct)
class Attr4(object):
__metaclass__ = AttrMeta
print Attr4().func1(), Attr4().func2()
Although it's not very elegant, you can use locals()
:
>>> class c(object):
... for i in range(10):
... locals()['A' + str(i)] = i
...
>>> c.A0
0
>>> c.A7
7
I don't exactly know, what you are doing. I can give you example of adding class attributes to a class in a for loop:
attributes = ('x', 5), ('y', 6), ('name', 'Cls')
class Cls:
pass
for key, value in attributes:
setattr(Cls, key, value)
Remember that for must be run after whole class is defined. You get error, that attr is not defined, because you want to access the class before you create it (class ...
is a statement in python, which creates a class object). You must add attributes after you create a class and rememeber, those will be class attributes, not instance attributes.