python 定义类时在python中设置具有给定名称的类属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2519807/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-04 00:50:10  来源:igfitidea点击:

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

pythonclasssetattr

提问by prismofeverything

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 setattrto work the same as just assigning a variable in the class definition. How can I do this?

但我似乎无法找到对类的引用,setattr以使其与仅在类定义中分配变量一样工作。我怎样才能做到这一点?

采纳答案by Ignacio Vazquez-Abrams

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

回答by Vitalik Verhovodov

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

与之前的答案相反,此解决方案适用于外部元类(例如,Django 模型)。

回答by keturn

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

这可能是因为A当你在setattr(A, p, v)那里做你的时候这个类没有完全初始化。

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

首先要尝试的是在关闭class块后将 settattr 向下移动,看看是否有效,例如

class A(object):
    pass

setattr(A, property, value)

Otherwise, that thing Ignacio just said about metaclasses.

否则,Ignacio 刚刚说的关于元类的那件事

回答by StoneyD

So I know this is really old and probably beating a dead horse and this may not have been possible at the time but I cam across this trying to solve my own problem.

所以我知道这真的很旧,可能会打败一匹死马,这在当时可能是不可能的,但我遇到了这个试图解决我自己的问题。

I realized this can be accomplished without metaclassing.

我意识到这可以在没有元类的情况下完成。

The setattr takes and object, accessor name, and value. Well the object is not the class name it's the specific instance of the class, which can be accomplished with self.

setattr 接受对象、访问器名称和值。那么对象不是类名,它是类的特定实例,这可以通过 self 来完成。

class A(object):
    def __init__(self):
        self.a = 'i am a accessor'
        setattr(self, 'key', 'value')

a = A()
print a.a
print a.key