class Something: pass
f=lambda : True
現在,如果我這樣做了
Something.open=f
g=Something()
g.open()
我得到一個錯誤,TypeError: <lambda>() takes 0 positional arguments but 1 was given
和g.open
是<bound method <lambda> of <__main__.Something object at 0xffff80253400>>
。這意味著傳遞給打開的self
對象。
然而,如果我這樣做了
Something.open=open
g=Something()
g.open()
我只是得到一個錯誤TypeError: open() missing required argument 'file' (pos 1)
,g.open
只是<built-in function open>
,因為可能沒有給open
參數。
為什么會有差異?
后續:我可以讓f
像built-in函數一樣工作嗎(也就是說,不向它傳遞self
對象)?
我不知道你為什么要這樣做,但你可以這樣做: