views:

106

answers:

2

I am trying to do something like this:

property = 'name'
value = Thing()
class A:
  setattr(A, property, value)
  other_thing = 'normal attribute'

  def __init__(self, etc)
    #etc..........

But I can't seem to find the reference to the class to get the setattr to work the same as just assigning a variable in the class definition. How can I do this?

+4  A: 
keturn
+1 for simplest solution
Piotr Czapla
This solution works very well. There is no need to do this in a metaclass when you can do it directly.
Mike Graham
+2  A: 

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__ = MC

print C.foo
Ignacio Vazquez-Abrams