Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 466
prismofeverything Avatar asked Mar 25 '10 22:03

prismofeverything


2 Answers

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

like image 79
Vitalik Verhovodov Avatar answered Sep 28 '22 20:09

Vitalik Verhovodov


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
like image 40
Ignacio Vazquez-Abrams Avatar answered Sep 28 '22 20:09

Ignacio Vazquez-Abrams