As an example, say I would like to decorate split()
method of str
class.
(the example is representative of what I try to do, except I would like to decorate agg
method of pandas DataFrame
class :) )
至少,我得到同样的错误。
I prefer not to use @
nor to create a child of str
class to keep things simple (and maybe it is why it is not working...)
我首先有一个问题:不能修改装饰器的参数吗?
def bla_addition(word):
def decorator(func):
def wrapper(*args, **kwargs):
# Modify `my_list`
word += 'bla' #-> parameter word modified
return word.func(*args, **kwargs)
return wrapper
return decorator
added = bla_addition('blu')
split = added(str.split)
new_word = split('l')
Error generated: UnboundLocalError: local variable 'word' referenced before assignment
我很好奇知道为什么?
好的,因此为了绕过这个缺点,我创建了一个新的局部变量,但遇到了以下麻烦。
def bla_addition(word):
def decorator(func):
def wrapper(*args, **kwargs):
# Modify `my_list`
word2 = word + 'bla' #-> local word2 used
return word2.func(*args, **kwargs)
return wrapper
return decorator
added = bla_addition('blu')
split = added(str.split)
new_word = split('l')
Error encountered: AttributeError: 'str' object has no attribute 'func'
拜托,你知道我该怎么办吗?
感谢您的帮助和建议。
PS: I took the way of using decorator without @
here:
https://www.python-course.eu/python3_decorators.php
I find it very helpful to avoid having to create a new 1-line function for split
.