2 回答
TA貢獻(xiàn)1851條經(jīng)驗(yàn) 獲得超3個(gè)贊
為了解決這個(gè)問(wèn)題,我們可以利用Python裝飾器只是返回其他函數(shù)的函數(shù)的事實(shí)。
假設(shè)您有以下裝飾器:eggs
def eggs(foo=10, bar=20):
def wrapper_gen(func):
def wrapper(*args):
print(foo, bar)
func(*args)
return wrapper
return wrapper_gen
這個(gè)類:Spam
class Spam:
@eggs(foo=10, bar=20)
def baz(self, input):
print(input)
我們可以這樣調(diào)用該方法:baz
Spam().baz("Hello, world!")
這給了我們
10 20
Hello, world!
現(xiàn)在,我們將在我們的方法中裝飾,而不是直接修飾函數(shù):__init__
class Spam:
def __init__(self, foo=10, bar=20):
self.baz = eggs(foo=foo, bar=bar)(self._baz_func)
def _baz_func(self, input):
print(input)
現(xiàn)在:
Spam(foo=20, bar=30).baz("Hello, world!")
此輸出
20 30
Hello, world!
這有效的原因是:
@foo
def bar():
...
是以下的簡(jiǎn)寫(xiě):
def bar():
...
bar = foo(bar)
TA貢獻(xiàn)1836條經(jīng)驗(yàn) 獲得超13個(gè)贊
這不能使用常規(guī)的裝飾器語(yǔ)法工作,原因有兩個(gè):屬于類,所以它不能對(duì)不同的實(shí)例有不同的行為,因?yàn)樗挥幸粋€(gè)“副本”;并且裝飾器是在類聲明時(shí)執(zhí)行的,而不是在創(chuàng)建實(shí)例時(shí)執(zhí)行的,因此還沒(méi)有參數(shù)。get_some_value__init__
但是,您可以通過(guò)在方法中顯式應(yīng)用修飾器來(lái)獲得所需的結(jié)果:__init__
class Access:
def __init__(self, maxsize: int = 5, ttl: int = 10):
decorator = cached(cache=TTLCache(maxsize=maxsize, ttl=ttl))
self.get_some_value = decorator(self.get_some_value)
def get_some_value(self, input: str):
...
添加回答
舉報(bào)
