尝试使用decorator函数参数时发生UnboundLocalError

2024-05-23 20:01:31 发布

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

我一直在尝试使用Python的decorator函数来创建一个完全愚蠢的项目,但是我遇到了这个错误

UnboundLocalError: local variable 'mana_cost' referenced before assignment

我也不确定到底怎么了。以下是迄今为止的代码(甚至不确定它是否起作用,WIP obvs):

from stuff.mana_pool import ManaPool

def spell(mana_cost):
    def decorator(func):
        def wrap(*args, **kwargs):
            print(mana_cost)
            mana_pool = kwargs['mana_pool']
            cost = {}
            for mana_type in ['W', 'U', 'B', 'R', 'G']:
                cost[mana_type] = mana_cost.count(mana_type)
                mana_cost = mana_cost.replace(mana_type, '')
            cost['generic'] = int(mana_cost)
            func(*args, **kwargs)
        return wrap
    return decorator

my_pool = ManaPool()

@spell("2BB")
def func(thingy):
    print(thingy)

func('boop', mana_pool=my_pool)

有什么想法吗?你知道吗


Tags: returnmydeftypeargsdecoratorkwargsfunc