當我嘗試在裝飾中裝飾具有參數的方法時,它給我一個self
未定義。如果改爲將類別val
更改爲類變量並使用MyCls.val
它現在給我MyCls未定義!我如何裝飾我的mehtod?使用args獲取裝飾器以使用方法:self不存在
def dodecorate(VAL):
def decorate(func):
def wrapped(*args,**kwargs):
res = func(*args,**kwargs)
if res == VAL:
res = "one"
return res
return wrapped
return decorate
class MyCls(object):
def __init__(self):
self.val = 1
@dodecorate(VAL = self.val)
def onefrom1(self, x):
return x
EDIT上面是一個抽象我發明來表示原。這是實際的代碼。
def retry_on_invalid_schema(MAX_RETRIES):
def retrier(func):
def wrapped(*args, **kwargs):
tries = 0
res = None
while tries < MAX_TRIES:
try:
res = func(*args, **kwargs)
assert res.has_key('by')
assert res.has_key('id')
break
except AssertionError:
res = None
time.sleep(2**tries)
tries += 1
continue
return res
return wrapped
return retrier
class Base(object):
def __init__(self):
self.MAX_RETRIES = 3
@retry_on_invalid_schema(MAX_RETRIES = self.MAX_RETRIES)
def _get_api_response(self, uri):
return json.loads(self._get(uri))
def _get(self, uri):
return requests.get(uri).text
你可以顯示你的'實例'嗎? – Yax 2014-11-24 15:32:55
@Yax我有機會實例化它之前得到錯誤。 – pad 2014-11-24 15:34:34
在類定義期間調用裝飾器函數時,不會存在'self'和'MyCls'。你真的想在這裏做什麼? – jonrsharpe 2014-11-24 15:39:54