[英]how to define a decorator for class to decorate class method
我想在 class 方法中添加一些固定變量。 但是我不想在每次使用時都傳遞這些變量。 我不能直接裝飾 class 方法,因為我的 class 是一個子 class 並且我不能修改父 ZA2F2ED4F8EBC2CBB4C21A29 這是我想嘗試的:
def callable(o):
return hasattr(o, "__call__")
def trace(f):
def traced(*args, **kw):
"Print message before and after a function call."
print("Entering", f.__name__)
kw['new value'] = 'new value'
result = f(*args, **kw)
print("Leaving", f.__name__)
return result
return traced
def mtrace(cls):
for key, val in cls.__dict__.items():
if key.startswith("__") and key.endswith("__") or not callable(val):
continue
print('calling in mtrace', key)
setattr(cls, key, trace(val))
print("Wrapped", key)
return cls
class dull:
@classmethod
def method1(cls, **arg):
print("Method 1 called with arg", arg)
@mtrace
class myclass(dull):pass
myclass.method1(a='hello')
output 是:
try class method
Method 1 called with arg {'a': 'hello'}
新值不會添加到方法 1。 我不太明白 python 解釋器如何調用 class 方法。 如果有人可以幫助我,非常感謝。
我嘗試使用 super 重新定義父 class。 它按我的意願工作。 但我沒有使用裝飾器。 但它看起來並不漂亮。
class BaseRequest: # cannot modify this class
@classmethod
def http_get(cls, *vars, **kws):
print("Method 1 called with arg", kws)
class MyRequest(BaseRequest):
extra_vars = {}
@classmethod
def http_get(cls, *vars, **kws):
kws.update(cls.extra_vars)
super().http_get(*vars, **kws)
@classmethod
def set_extra_vars(cls, **kws):
cls.extra_vars.update(kws)
MyRequest.set_extra_vars(header='my hearders')
MyRequest.http_get(a='hello')
使用 arg {'a': 'hello', 'header': 'my hearers'} 調用的輸出方法 1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.