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):
Menu