0

Sometimes I need to create new variables with a suffix using a variable, which I can with something like:

Number=5
locals()['First'+str(Number)]=5

Resulting in the variable First5 which is = 5.

How can I do the same thing in a class instance?

class foo:
    def appender(self,bar):
        for i in range(bar):
            self.locals()['Number'+str(i)]=i
#-----
qq=foo()
qq.appender(3) #issues...

I would like this to create qq.Number0, qq.Number1 and qq.Number2, but it tells me that foo has no instance of locals. How can I concatenate strings to create new variables in my instance? Thanks!

Q-man
  • 2,069
  • 1
  • 17
  • 16
  • Are you looking for `foo.__dict__`, or `self.__dict__`? – MrAlias Jul 06 '14 at 04:16
  • I think I am looking for self.__dict__, as I only want it associated with the instance. Each instance may have a different number of 'bar', but maybe I'm just confused... – Q-man Jul 06 '14 at 04:19
  • I think I get it. You want to dynamically set an attribute of a class so that the name is also created from the value, right? – MrAlias Jul 06 '14 at 04:23

1 Answers1

0

To dynamically set attributes of a class instance you can use the internal method __setattr__.

class Foo(object):
    def appender(self, bar):
        self.__setattr__('Number' + str(bar), bar)

Which should give you:

>>>> foo = Foo()
>>>> foo.appender(1)
>>>> foo.Number1
1
MrAlias
  • 1,316
  • 15
  • 26
  • Thank you MrAlias - I think this is the right path, although Python tells me thatfoo has no attribute '__setattr__'. – Q-man Jul 06 '14 at 04:37
  • the underscores are important: `setattr != __setattr__` – MrAlias Jul 06 '14 at 04:38
  • Also make sure that you using the _new_ class style in python2 (i.e. `class foo(object):`) – MrAlias Jul 06 '14 at 04:40
  • 1
    That is it! I was creating my class with foo() and not foo(object). Now the settattr is there. THANK YOU! – Q-man Jul 06 '14 at 04:42
  • yes this indeed looks like you are using the [old class type](http://stackoverflow.com/questions/54867/old-style-and-new-style-classes-in-python). – MrAlias Jul 06 '14 at 04:42