这是Python 2.5,它也是GAE,并不重要.
我有以下代码.我正在使用dec_check类作为装饰器在bar中装饰foo()方法.
class dec_check(object):
def __init__(self, f):
self.func = f
def __call__(self):
print 'In dec_check.__init__()'
self.func()
class bar(object):
@dec_check
def foo(self):
print 'In bar.foo()'
b = bar()
b.foo()
Run Code Online (Sandbox Code Playgroud)
执行此操作时,我希望看到:
In dec_check.__init__()
In bar.foo()
Run Code Online (Sandbox Code Playgroud)
但我得到" TypeError: foo() takes exactly 1 argument (0 given)"作为.foo()一种对象方法,以自我为参数.我猜测问题是bar当我执行装饰器代码时,实例并不存在.
那么如何将一个实例传递bar给装饰器类呢?
__repr__用于返回对象的字符串表示,但在 Python 中,函数也是对象本身,并且可以具有属性。
如何设置__repr__函数的?
我在这里看到可以为函数外部的函数设置一个属性,但通常__repr__在对象定义本身内设置一个属性,所以我想在函数定义本身内设置 repr。
我的用例是,我正在使用Tenacity重试具有指数退避功能的网络函数,并且我想记录我最后调用的函数的(信息性)名称。
retry_mysql_exception_types = (InterfaceError, OperationalError, TimeoutError, ConnectionResetError)
def return_last_retry_outcome(retry_state):
"""return the result of the last call attempt"""
return retry_state.outcome.result()
def my_before_sleep(retry_state):
print("Retrying {}: attempt {} ended with: {}\n".format(retry_state.fn, retry_state.attempt_number, retry_state.outcome))
@tenacity.retry(wait=tenacity.wait_random_exponential(multiplier=1, max=1200),
stop=tenacity.stop_after_attempt(30),
retry=tenacity.retry_if_exception_type(retry_mysql_exception_types),
retry_error_callback=return_last_retry_outcome,
before_sleep=my_before_sleep)
def connect_with_retries(my_database_config):
connection = mysql.connector.connect(**my_database_config)
return connection
Run Code Online (Sandbox Code Playgroud)
目前retry_state.fn显示<function <lambda> at 0x1100f6ee0>类似于@chepner 所说的内容,但我想向其中添加更多信息。