2 回答

TA貢獻1805條經驗 獲得超10個贊
您在將靜態方法用作默認參數時遇到問題的原因是兩個問題的組合。
第一個問題是,在def語句運行時需要很好地定義默認參數,而不僅僅是在調用函數時。那是因為默認參數被內置到函數對象中,而不是在每次函數運行時重新計算(這也是為什么像空列表這樣的可變默認參數通常是錯誤的原因)。無論如何,這就是您不能MyClass.static_method用作默認參數的原因,因為MyClass在定義函數時尚未定義(類對象僅在其所有內容都已創建后生成)。
下一個問題是staticmethod對象不具有與常規函數相同的屬性和方法。通常這無關緊要,因為當您通過類對象(例如,MyClass.static_method一旦MyClass存在)或通過實例(例如self.static_method)訪問它時,它將是可調用的并且具有__name__. 但那是因為您在這些情況下獲得了底層功能,而不是staticmethod對象本身。該staticmethod對象本身是一個描述符,而不是調用。
所以這兩個函數都不能正常工作:
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對象底層的實際函數作為默認值:
def baz(self, func=static_method.__func__): # this works!
name = func.__name__
func()
與使用name = func.__func__.__name__.
添加回答
舉報