你能告訴我們,如果這始終是最後一個參數?如果沒有,你必須使用它的名字。
我的想法是這樣:
def check_orc(orc):
if isinstance(orc, int):
orc = str(orc)
print DeprecationWarning("You should not be sending snaga to combat")
return orc
def check_opp(meth):
code = meth.func_code
argnames = code.co_varnames[:code.co_argcount]
if 'opponent' in argnames:
from functools import wraps
argidx = argnames.index('opponent')
@wraps(meth)
def replace(*a, **k):
if 'opponent' in k:
k['opponent'] = check_orc(k['opponent'])
else:
a = list(a)
a[argidx] = check_orc(a[argidx])
a = tuple(a)
return meth(*a, **k)
return replace
else:
return meth
class Warrior():
@check_opp
def slash_orc(self, sword, shield, opponent):
print "slash", (sword, shield, opponent)
@check_opp
def hack_orc(self, warhammer, opponent):
print "hack", (warhammer, opponent)
Warrior().slash_orc(1,3,4)
Warrior().hack_orc(6,5)
Warrior().slash_orc(1,3,opponent=4)
Warrior().hack_orc(6,opponent=5)
Warrior().slash_orc(1,3,"4")
Warrior().hack_orc(6,"5")
Warrior().slash_orc(1,3,opponent="4")
Warrior().hack_orc(6,opponent="5")
這是一個非常醜陋的黑客攻擊,但仍然應該工作,並從重新排序的參數爲您節省。
這裏我使用一種檢查來找到正確的參數並對其進行修改,而不管它是否已經作爲關鍵字或索引參數傳遞。
請注意,我稍微更改了測試以使其適用於我(我「棄用」整數並且需要strs)。你只需要我的check_opp()
功能,並將其應用於任何你需要的地方。
將最常用的參數添加到自我,這樣您就可以避免將所有方法都傳遞給 – avasal 2012-08-08 08:45:27
,或者通過sed命令很難編輯您的源代碼。這不是乾的,但更易讀和可維護。 – fanlix 2012-08-08 08:59:24
我不明白 - 當它是實例的外部實體時,如何將參數添加到'self'? – Kimvais 2012-08-08 09:41:08