python - Python - 更新分配给 var 的函数/返回
问题描述
先写代码,这样你就会明白我在说什么:
goal = False
count = 0
def function():
if goal==True:
return True
else:
return False
def func():
if dict1["A"]==True:
return True
else:
return False
dict1 = {"A":function()}
dict2 = {"B":func()}
list = [dict1,dict2]
goal = True
for i in list:
count = 0
for x,y in i.items():
if y==True:
count+=1
if count==len(i):
print("Works")
else:
print(i)
>>>{"A":False}
>>>{"B":False}
这不是我当前的代码,但它是实际问题。这就是我要问的地方,如何更新字典中的值。我应该做类似的事情:
for i in list:
for x,y in i.items():
y()
?
我当前的项目在 Ren'Py (.rpy) 中使用,但由于我使用的是 python 块,因此代码的工作方式与普通 Python 完全相同。在名为 Event 的类中,我的元素完全如下:
def ev_check(self):
if self.done==False:
self.count = 0
for x,y in self.conditions.items():
if y==True:
self.count+=1
else:
pass
if self.count==len(self.conditions):
self.valid = True
else:
self.valid = False
else:
self.valid = False
def own_office():
if Promotion_1.done==True: #Once the event is played, .done gets True
return True
else:
return False
def times_worked(x):
if You.worked < x:
return False
else:
return True
Promotion_1.conditions = {"Work 2 times" : times_worked(2)}
Meet_Tigerr.conditions = {"Own office" : own_office()}
#External event that adds a value to the data named You.worked to get it to 2
print(Promotion_1.conditions["Work 2 times"])
>>> False
预期结果:真 结果:假
解决方案
您可以创建自定义字典并拥有此功能。你可以尝试这样的事情:
class MyDict(dict):
def __getitem__(self, item):
val = super().__getitem__(item)
if callable(val):
return val()
return val
它的工作方式与 dict 完全相同,只是它每次都会为您调用可调用值。
d = MyDict()
d['m'] = 1
d['m']
Out[28]: 1
task
Out[33]: <function __main__.task()>
task()
Out[34]: True
d['t'] = task
d['t']
Out[36]: True
编辑:修改了代码以显示如何为参数化函数传递参数值:
def func():
return True
def param_func(i):
return 2*i
def param_func2(i, j):
return i*j
class MyDict(dict):
def __getitem__(self, key):
if isinstance(key, tuple):
super_key = key[0]
else:
super_key = key
super_val = super().__getitem__(super_key)
if callable(super_val):
if isinstance(key, tuple):
args = key[1:]
return super_val.__call__(*args)
else:
return super_val.__call__()
return super_val
if __name__ == "__main__":
d = MyDict()
d['num'] = 1
print(d['num'])
d['func'] = func
print(d['func'])
d['param_func'] = param_func
print(d['param_func', 2])
d['param_func2'] = param_func2
print(d['param_func2', 2, 6])
输出 :
1
真的
4
12
推荐阅读
- multithreading - 如何使用谷歌表格的谷歌应用脚本制作简单的多线程
- python - PyQt5 QMYSQL 驱动程序未加载
- python - 从 pandas DataFrame 计算 RSI 指标?
- xaml - Android 中的 Xamarin 窗体框架
- batch-file - 如何在限制范围内生成随机数?
- javascript - 删除特殊字符 Javascript
- r - 如何将时间添加到 netcdf 文件?
- mysql - 这个版本的 MariaDB 还不支持 'LIMIT & IN/ALL/ANY/SOME 子查询' - Multiple WHEREs and LIMITS
- python - 无法使用 igraph 函数“all_simple_paths”
- java - .NET 中的不可变列表:为什么允许添加和删除项目?