[英]How to add method to base class?
我想將__add__
和__radd__
添加到 python base class set
中。
代碼可以很簡單
def __add__(self, other) :
assert isinstance(other, set), \
"perhaps additional type checking or argument validation can go here but" + \
" strictly only defined for pure python sets"
return set( list(self) + list(other) )
def __radd__(self, other) :
assert isinstance(other, set), \
"perhaps additional type checking or argument validation can go here but" + \
" strictly only defined for pure sets"
return set( list(other) + list(self) )
這個的 pythonic 實現是什么?我如何在不創建自己的MySet
class 的情況下擴展基數 class,將set
作為父 class? 我可以只使用set.__add__ = some_function_I_defined
嗎?
恕我直言,你應該做的是將內置set
class 子類化。在 Python 中(與 Ruby 或 JavaScript 相反)猴子修補內置是不允許的。
因此,例如嘗試添加一個不存在的方法:
x = [1,2,3]
x.my_new_method_added_in_runtime = lambda: "whatever"
不會工作,你會得到AttributeError: 'list' object has no attribute 'my_new_method_added_in_runtime'
您也不能修改使用這些內置函數實例化的對象的現有方法:
x = [1,2,3]
x.sort = lambda: "returning some string instead of sorting..."
將導致AttributeError: 'list' object attribute 'sort' is read-only
和
list.append = None
# OR
del list.append
將導致: TypeError: can't set attributes of built-in/extension type 'list'
以上所有內容都適用於set
以及依此類推。
您可以嘗試尋找一些庫來實現該目標,例如https://pypi.org/project/forbiddenfruit/0.1.0/ ,但強烈建議不要這樣做。
@chepner 在沒有意識到的情況下正確地回答了我的問題。 因為我不熟悉 python 集,所以我試圖重新實現現有的功能。
加入兩個集合的行為,“合並”是通過 python __or__
和__ior__
方法實現的。 我特別需要的操作是|
和|=
。
原則上,我們應該能夠按照 chepner 的建議設置操作set.__add__ = set.__or__
,但正如 chepner 指出的那樣,這會導致錯誤:
TypeError: cannot set '__add__' attribute of immutable type 'set'
謝謝你們。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.