簡體   English   中英

UnboundLocalError:具有默認參數的Decorator

[英]UnboundLocalError: Decorator with default parameters

這是我的裝飾代碼。 我出於某種原因得到UnboundLocalError但我找不到它。

>>> def validate(schema=None):
        def wrap(f):
            def _f(*args, **kwargs):
                if not schema:
                schema = f.__name__
            print schema
            return f()
            return _f
        return wrap

>>> @validate()
    def some_function():
        print 'some function'


>>> some_function()
Traceback (most recent call last):
  File "<pyshell#27>", line 1, in <module>
    some_function()
  File "<pyshell#22>", line 4, in _f
    if not schema:
UnboundLocalError: local variable 'schema' referenced before assignment
>>> 

所以,我想也許最好在這里發帖。 我可能會遺漏一些東西。

謝謝。

編譯器無法確定schema的適當范圍。 要么使用nonlocal schema中(3.X) _f()或更改的定義_f()咯:

def _f(self, schema=schema, *args, **kwargs):

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM