A python problem on lazy assignment

here I abstract the actual business
I try to create a class that has the following methods:

import types


class A:
    def __init__(self,num):
        self.num = num
        self.add_prop(10)    -sharp 10
        
    def add_prop(self, n):
        for i in range(n):
            fun_name = "add_" + str(n)    -sharp 
            
            def add_fun(self):
                return self.num + i
                
            setattr(self, fun_name, types.MethodType(add_fun, self))    -sharp 

seems logically that the above code does what I want, and it does give class A 10 attributes of add_n , but in fact these methods are the same and cannot return predetermined values on demand. For example, add_1 , we expect it to return self.num + 1 , but in fact it returns self.num + 10 , that is, the Mantissa of the loop 10 in for i in range (10) .

  • so how should I write to avoid this situation, or is there any other better way to implement it?

this is a closure problem, which solves

...
def wrapper(i):
    def add_fun(self):
        return self.num + i
    return add_fun
setattr(..., wrapper(i), ...)
...

def add_fun(self):
Change

to

def add_fun(self, i=i):
MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1e76ebe-616.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1e76ebe-616.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?