Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
我有一个使用 定义的 python 类__slots__,如下所示:
__slots__
class TheClass: __slots__=['foo','bar']
我想按名称设置它的值,就像这样
the_object=TheClass() for x in ['foo','bar']: the_object[x]=x+x
那可能吗?
与一般情况没有区别,您可以使用getattrand setattr:
getattr
setattr
the_object=TheClass() for attname in ['foo','bar']: setattr(the_object, attname, attname+attname)
你会得到:
>>> the_object.foo 'foofoo'