0

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?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
yigal
  • 3,923
  • 8
  • 37
  • 59
  • 2
    Out of curiosity, why are you using `__slots__`? – DSM Dec 12 '13 at 22:20
  • i like the idea of static typing - i want to know in advance what are the data members of my classes are. I think it help in understanding code – yigal Dec 12 '13 at 22:22
  • 1
    You'd use `setattr()`, or if you want to be obscure, use the slot descriptors: `TheClass.__dict__[x].__set__(the_object, x + x)`. But you don't, not really. – Martijn Pieters Dec 12 '13 at 22:22
  • @yigalirani: Don't. Only use `__slots__` if you need to save memory; e.g. when you have *loads* of `TheClass` instances. – Martijn Pieters Dec 12 '13 at 22:23
  • @Martijn Pieters, why? are there some drawbacks for using __slots__? – yigal Dec 12 '13 at 22:25
  • 2
    @yigalirani: Python is dynamically typed, and many of its best features are built around that fact. Trying to force it to be otherwise means you're giving yourself the worst of both worlds. – abarnert Dec 12 '13 at 22:25
  • @abarnert, any specific example? are there some code constructs that will fail if i use __slots_? – yigal Dec 12 '13 at 22:26
  • @yigalirani the most notable thing is that it breaks pickling. – roippi Dec 12 '13 at 22:34
  • @roippi: Yes. But more abstractly, it prevents you from designing your APIs around flexible duck-typing. If you have some function that naturally works with anything with a `foo` attribute that represents the amount of spam in the object, and has no interest in whether `bar` exists or what it means, you shouldn't write it in terms of a Java-style "interface" that has both `foo` and `bar`. (And even when such an interface is exactly what you need, it's usually the methods rather than the attributes that you care about, and [ABCs](http://docs.python.org/2/library/abc.html) are the answer.) – abarnert Dec 12 '13 at 23:30

1 Answers1

3

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'
alko
  • 46,136
  • 12
  • 94
  • 102