在定义类时在 python 中设置具有给定名称的类属性
我正在尝试做这样的事情:
property = 'name'
value = Thing()
class A:
setattr(A, property, value)
other_thing = 'normal attribute'
def __init__(self, etc)
#etc..........
但我似乎找不到对类的引用来让 setattr
与在类定义中分配变量一样工作。我该怎么做?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以做得更简单:
与之前的答案相比,此解决方案可以很好地与外部元类(例如 Django 模型)配合使用。
You can do it even simpler:
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:
这可能是因为当您在那里执行
setattr(A, p, v)
时,类A
尚未完全初始化。首先要尝试的是将 settattr 向下移动到关闭
class
块后,看看是否有效,例如否则,
This may be because the class
A
is not fully initialized when you do yoursetattr(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.Otherwise, that thing Ignacio just said about metaclasses.
所以我知道这真的很老了,可能已经死了,这在当时可能是不可能的,但我在试图解决我自己的问题时遇到了这个问题。
我意识到这可以在没有元类的情况下完成。
setattr 接受对象、访问器名称和值。好吧,对象不是类名,而是类的特定实例,这可以通过 self 来完成。
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.