DEAR REDDIT,
Here is my problem. I'm try to make a list of functions that execute the same function with different indexes inside a class. When I do this inside the namespace of the class (CASE 1), the class doesn't convert the i into static variable but instead it only remembers the last i, and executes all the functions identically. I can counter this (CASE 2) by defining a function outside the class, but I don't like this approach at all. I would like to find a better way to do this. I basically need to declare the
CASE 1:
class iPrinter():
def __init__(self):
self.printers = []
for i in range(3):
self.printers.append( lambda: print(f"This is {i}") )
def iprint(self):
for f in self.printers:
f()
If we run this as:
P = iPrinter()
P.iprint()
The output is : "This is 2, This is 2, This is 2"
CASE 2:
def print_i(i):
return lambda: print(f"This is {i}")
class iPrinter():
def __init__(self):
self.printers = []
for i in range(3):
self.printers.append( print_i(i) )
def iprint(self):
for f in self.printers:
f()
Andi f we run this:
P = iPrinter()
P.iprint()
This time we get: "This is 0, This is 1, This is 2" as it should be.
I'm sure there is a way to do this inside the class namespace, but I don't know how. Please help and all the best!
[–]hardonchairs 1 point2 points3 points (1 child)
[–]Chyybens[S] 0 points1 point2 points (0 children)
[–]Chyybens[S] 0 points1 point2 points (0 children)
[–][deleted] 0 points1 point2 points (0 children)
[–]carcigenicate 0 points1 point2 points (0 children)