python装饰器从何处获得装饰函数的参数
我有以下代码:python装饰器从何处获得装饰函数的参数,python,decorator,python-decorators,Python,Decorator,Python Decorators,我有以下代码: def foo(bar): def test(some_string): return 'Decorator test: '+bar(some_string) return test def main(): print(bar('test1')) @foo def bar(some_string): return some_string[:3] 我知道调用bar('test1)基本上就是调用foo(bar('test1')
def foo(bar):
def test(some_string):
return 'Decorator test: '+bar(some_string)
return test
def main():
print(bar('test1'))
@foo
def bar(some_string):
return some_string[:3]
我知道调用bar('test1)
基本上就是调用foo(bar('test1'))
,但是当我试图在另一个函数之前在foo
中打印一些字符串时,我得到一些字符串没有定义
:
def foo(bar):
print(some_string)
def test(some_string):
return 'Decorator test: '+bar(some_string)
return test
test
如何知道某些字符串而foo
不知道
为什么我必须返回test
,装饰师才能工作?直接返回Decorator测试:'+bar(某些字符串)
不起作用,因为未定义some字符串
我知道调用bar('test1')
基本上就是调用foo(bar('test1'))
不,不是,你的理解是错误的。它基本上是在打电话
foo(bar)('test')
@foo
decorator语法告诉Python调用foo()
,传入由bar
命名的函数对象(结果被分配回名称bar
)
foo()
decorator返回了一个新的函数对象:
def test(some_string):
# ...
return test
因此foo(bar)
的结果是名为test
的函数对象(在foo()
装饰器中的本地名称)foo(bar)('test')
因此被称为test('test')
如果要打印传递给测试(..)
的参数,请在该函数内执行以下操作:
def foo(bar):
def test(some_string):
print(some_string)
return 'Decorator test: '+bar(some_string)
return test
我知道调用bar('test1')
基本上就是调用foo(bar('test1'))
不,那是不正确的
调用bar('test1')
相当于
bar = foo(bar)
bar('test1')
为什么我必须返回test
,装饰师才能工作?直接返回Decorator test:“+bar(某些_字符串)不起作用,因为未定义某些_字符串
当你这样做的时候
@decorator
def func():
pass
Python将其转换为
def func():
pass
func = decorator(func)
如您所见,Python希望decorator
返回一个新的函数。这就是为什么必须从foo
返回test
,才能使bar
正常工作的原因。否则,None
将分配给bar
:
>>> def foo(bar):
def test(some_string):
return 'Decorator test: '+bar(some_string)
>>> @foo
def bar(some_string):
return some_string[:3]
>>> bar()
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
bar()
TypeError: 'NoneType' object is not callable
不。它是foo(bar)('test1')
。
def foo(bar):
def test(some_string):
print(some_string)
return 'Decorator test: '+bar(some_string)
return test