2 回答

TA貢獻(xiàn)1805條經(jīng)驗(yàn) 獲得超10個(gè)贊
您在將靜態(tài)方法用作默認(rèn)參數(shù)時(shí)遇到問(wèn)題的原因是兩個(gè)問(wèn)題的組合。
第一個(gè)問(wèn)題是,在def語(yǔ)句運(yùn)行時(shí)需要很好地定義默認(rèn)參數(shù),而不僅僅是在調(diào)用函數(shù)時(shí)。那是因?yàn)槟J(rèn)參數(shù)被內(nèi)置到函數(shù)對(duì)象中,而不是在每次函數(shù)運(yùn)行時(shí)重新計(jì)算(這也是為什么像空列表這樣的可變默認(rèn)參數(shù)通常是錯(cuò)誤的原因)。無(wú)論如何,這就是您不能MyClass.static_method用作默認(rèn)參數(shù)的原因,因?yàn)镸yClass在定義函數(shù)時(shí)尚未定義(類對(duì)象僅在其所有內(nèi)容都已創(chuàng)建后生成)。
下一個(gè)問(wèn)題是staticmethod對(duì)象不具有與常規(guī)函數(shù)相同的屬性和方法。通常這無(wú)關(guān)緊要,因?yàn)楫?dāng)您通過(guò)類對(duì)象(例如,MyClass.static_method一旦MyClass存在)或通過(guò)實(shí)例(例如self.static_method)訪問(wèn)它時(shí),它將是可調(diào)用的并且具有__name__. 但那是因?yàn)槟谶@些情況下獲得了底層功能,而不是staticmethod對(duì)象本身。該staticmethod對(duì)象本身是一個(gè)描述符,而不是調(diào)用。
所以這兩個(gè)函數(shù)都不能正常工作:
class MyClass:
@staticmethod
def static_method():
pass
def foo(self, func=MyClass.static_method): # won't work because MyClass doesn't exist yet
pass
def bar(self, func=static_method): # this declaration will work (if you comment out foo)
name = func.__name__ # but this doesn't work when the bar() is called
func() # nor this, as func is the staticmethod object
什么工作將使用staticmethod對(duì)象底層的實(shí)際函數(shù)作為默認(rèn)值:
def baz(self, func=static_method.__func__): # this works!
name = func.__name__
func()
與使用name = func.__func__.__name__.
添加回答
舉報(bào)