在定义类时在python中使用给定名称设置类属性 [英] Setting a class attribute with a given name in python while defining the class

查看:266
本文介绍了在定义类时在python中使用给定名称设置类属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试做这样的事情:

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

但是我似乎找不到对类的引用来使setattr起作用,就像在类定义中分配变量一样.我该怎么办?

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?

推荐答案

您需要为此使用元类:

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

这篇关于在定义类时在python中使用给定名称设置类属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆