0

我有一个使用 定义的 python 类__slots__,如下所示:

class TheClass:
   __slots__=['foo','bar']

我想按名称设置它的值,就像这样

the_object=TheClass()
for x in ['foo','bar']: 
  the_object[x]=x+x

那可能吗?

4

1 回答 1

3

与一般情况没有区别,您可以使用getattrand setattr

the_object=TheClass()
for attname in ['foo','bar']: 
    setattr(the_object, attname, attname+attname)

你会得到:

>>> the_object.foo
'foofoo'
于 2013-12-12T22:19:43.310 回答