Python 3.x python中lambda函数的引用问题
我将lambda传递给类,并得到类中不同对象的相同结果。这是我的密码Python 3.x python中lambda函数的引用问题,python-3.x,lambda,Python 3.x,Lambda,我将lambda传递给类,并得到类中不同对象的相同结果。这是我的密码 from datetime import datetime class Test: def __init__(self,fun): self.fun=fun def getDate(self): return self.fun(datetime.now()) hour=1 minute=30 t1 = Test(lambda x:x.replace(hour=hour,mi
from datetime import datetime
class Test:
def __init__(self,fun):
self.fun=fun
def getDate(self):
return self.fun(datetime.now())
hour=1
minute=30
t1 = Test(lambda x:x.replace(hour=hour,minute=minute))
hour=2
minute=30
t2 = Test(lambda x:x.replace(hour=hour,minute=minute))
print(t1.getDate())
print(t2.getDate())
输出:
2020-02-06 02:30:13.293611
2020-02-06 02:30:13.293659
2020-02-06 01:30:13.293611
2020-02-06 02:30:13.293659
预期输出:
2020-02-06 02:30:13.293611
2020-02-06 02:30:13.293659
2020-02-06 01:30:13.293611
2020-02-06 02:30:13.293659
在调用lambda之前,变量
hour
和minute
会发生变化
hour = 1
minute = 30
# the values of `hour` and `minute` right now are irrelevant
t1 = Test(lambda x: x.replace(hour=hour, minute=minute))
hour=2
minute=30
# the values of `hour` and `minute` right now are irrelevant
t2 = Test(lambda x: x.replace(hour=hour, minute=minute))
# the values of `hour` and `minute` RIGHT NOW are relevant
# and RIGHT NOW they are 2 and 30, respectively
print(t1.getDate())
print(t2.getDate())
lambda引用变量,但不复制它们的值。换句话说,使用lambda函数执行时的值,而不是设置它们时的值
您的选择:
- 硬编码lambda中的值:
t1 = Test(lambda x: x.replace(hour=1, minute=30))
- 改变执行顺序。在更改
和hour
的值之前调用lambdaminute
hour1 = 1 minute1 = 30 t1 = Test(lambda x: x.replace(hour=hour, minute=minute)) print(t1.getDate()) hour1 = 2 minute1 = 30
- 为每个lambda使用不同的变量名
hour1 = 1 minute1 = 30 t1 = Test(lambda x: x.replace(hour=hour1, minute=minute1)) print(t1.getDate())
- 使用不同的范围以避免lambda引用相同的
和小时
,例如通过使用函数。本质上,这就像使用不同的变量名分钟
def helper_function(hour, minute) return Test(lambda x: x.replace(hour=hour, minute=minute)) t1 = helper_function(1, 30) t2 = helper_function(2, 30) print(t1.getDate()) print(t2.getDate())