Python更新指定的函数/返回

2024-09-26 18:09:51 发布

您现在位置:Python中文网/ 问答频道 /正文

先编码好让你明白我在说什么:

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}

这不是我当前的代码,但它是实际问题。这就是我要问的,如何更新dicts中的值。我应该这样做吗:

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

预期结果:正确 结果:错误


Tags: inselffalsetrueforreturnifdef
1条回答
网友
1楼 · 发布于 2024-09-26 18:09:51

您可以创建自定义dict并具有此功能。您可以尝试以下操作:

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

True

4

12

相关问题 更多 >

    热门问题