i have a python class that is defined using __slots__, like so:

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

I would like to sets it values by name, like so

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

is that possible?

有帮助吗?

解决方案

No difference with general case, you can use getattr and setattr:

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

You'll get:

>>> the_object.foo
'foofoo'
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top