綁定未綁定方法:Pythonic 方法
在Python 中,嘗試將未綁定方法綁定到實例而無需將它們綁定到實例時,通常會帶來挑戰。不經意地打電話給他們。例如,當使用 wxPython 並希望將按鈕資料組織為元組的類別級清單時,就會出現此問題。
如介紹段落中所提到的,依賴 functools.partial 可以提供一種解決方法,但可能有更優雅和Pythonic的解決方案。幸運的是,存在一種有效的方法來綁定未綁定的方法而不呼叫它們。
Python 函數具有充當描述符的能力,使得可以透過呼叫它們的 get 方法來綁定它們。此方法可確保未綁定方法綁定到特定實例,從而允許其在沒有任何意外呼叫的情況下傳遞。
程式碼範例:
# Declare an unbound method
def some_method(self):
# Method implementation here
# Bind the unbound method to an instance
instance = MyClass()
bound_method = some_method.__get__(instance, MyClass)
# Continue passing around the bound method without calling it
結論:
按照描述使用get方法使您能夠將未綁定方法無縫綁定到實例,保留其未綁定狀態,並解決了使用wxPython按鈕時遇到的問題。
免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。
Copyright© 2022 湘ICP备2022001581号-3