Setting a class attribute with a given name in python while defining the class Setting a class attribute with a given name in python while defining the class python python

Setting a class attribute with a given name in python while defining the class


You can do it even simpler:

class A():    vars()['key'] = 'value'

In contrast to the previous answer, this solution plays well with external metaclasses (for ex., Django models).


You'll need to use a metaclass for this:

property = 'foo'value = 'bar'class MC(type):  def __init__(cls, name, bases, dict):    setattr(cls, property, value)    super(MC, cls).__init__(name, bases, dict)class C(object):  __metaclass__ = MCprint C.foo


This may be because the class A is not fully initialized when you do your setattr(A, p, v) there.

The first thing to try would be to just move the settattr down to after you close the class block and see if that works, e.g.

class A(object):    pass

setattr(A, property, value)

Otherwise, that thing Ignacio just said about metaclasses.