python - Creating instance-vars in a loop returns None objects -


i tried small trafficlight implementation , got following code:

def __init__(...):     ...     self.redlight = light(color = "red", master = self.frame)          self.redlight.place(x = 10, y = 10)     self.yellowlight = light(color = "yellow", master = self.frame)     self.yellowlight.place(x = 10, y = 40)     self.greenlight = light(color = "green", master = self.frame)     self.greenlight.place(x = 10, y = 70)     ... 

i got bored , tried define pretty redundant code in loop:

def __init__(...):     ...     self.redlight = none     self.yellowlight = none     self.greenlight = none      l in [[self.redlight, "red", 10],               [self.yellowlight, "yellow", 40],               [self.greenlight, "green", 70]]:         l[0] = light(color = l[1], master = self.frame)         l[0].place(x = 10, y = l[2])     ... 

my understanding is, same the first code example, turns out, not write instance variables. watched code in debugger, l[0] object light-object...

isn't python call-by-reference, l[0] should directly write instance variables?

that's setattr , getattr for:

def __init__(self):     l in [['redlight', "red", 10],               ['yellowlight', "yellow", 40],               ['greenlight', "green", 70]]:         setattr(self, l[0], light(color=l[1], master=self.frame))         getattr(self, l[0]).place(x=10, y=l[2]) 

because mentioned in comments assigning l[0] changes contents of local variable l doesn't set attributes on instance.

note boils down to:

>>> = 1 >>> b = >>> b = 2  # assigning new value "b" doesn't change "a"! >>> 1 

or:

>>> = 1 >>> b = [a] >>> b[0] = 2  # won't change "a". >>> 1 

so while can change attribute assigning self.redlight doesn't mean can change attribute assigning different value list contains reference value of self.redlight.


Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -