尝试使用装饰器函数参数时的UnboundLocalError

时间:2017-10-06 20:14:40

标签: python python-3.x python-decorators

我一直在尝试使用Python的装饰函数制作一个完全愚蠢的项目,但我一直在犯这个错误

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)

有什么想法吗?

0 个答案:

没有答案