如何在類定義後使類方法變爲靜態?換句話說,爲什麼第三種情況會失敗?從類之外的現有方法創建靜態方法? (「未綁定方法」錯誤)
>>> class b: ... @staticmethod ... def foo(): ... pass ... >>> b.foo() >>> class c: ... def foo(): ... pass ... foo = staticmethod(foo) ... >>> c.foo() >>> class d: ... def foo(): ... pass ... >>> d.foo = staticmethod(d.foo) >>> d.foo() Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unbound method foo() must be called with d instance as first argument (got nothing instead)
不應該是'd.foo.im_func'嗎? – 2012-01-19 01:44:40
是的,謝謝。固定! – kindall 2012-01-19 01:48:26
那麼,你需要用'staticmethod'來標記它們,以便在實例上對它們進行等價調用,而不僅僅是類本身。 'd.foo()'可以使用或不使用'staticmethod'包裝,但'd().foo()'會爆炸(它會嘗試傳遞'foo'不接受的'self')。當然,沒有實例相關的功能需要在實例上調用它們,但對於DRY,引用靜態方法的方法可以並應該將其稱爲self.foo()而不是顯式命名該類。 – ShadowRanger 2016-12-02 17:46:40