[英]Can I change the default __add__ method in Python?
是否可以更改默認的__add__
方法來執行除添加之外的其他操作?
例如,如果目標是這一行: 5+5
get The answer is 10
or anything else like 0
by changing __add__
to be xy
instead of x+y
?
我知道我可以在自己的課程中更改__add__
:
class Vec():
def __init__(self,x,y):
self.x = x
self.y = y
def __repr__(self):
return f'{self.x, self.y}'
def __add__(self, other):
self.x += other.x
self.y += other.y
return Vec(self.x,self.y)
v1 = Vec(1,2)
v2 = Vec(5,3)
v1+v2
# (6, 5)
我可以以某種方式針對默認的__add__
方法來改變它的行為嗎? 我直覺地認為__add__
是在每個默認數據類型中定義的,以返回特定的結果,但話又說回來, __add__
方法是我們在為特定的 class 更改它時要解決的問題,那么,是否可以更改主要的__add__
邏輯?
這些方面的東西?
class __add__():
...
是的,您可以重載用戶定義類中的任何內容。
class Vec():
def __init__(self,x,y):
self.x = x
self.y = y
def __repr__(self):
return f'{self.x, self.y}'
def __add__(self, other):
self.x += other.x
self.y += other.y
return Vec(self.x,self.y)
v1 = Vec(1,2)
v2 = Vec(5,3)
print(v1+v2)
# using lambda function
Vec.__add__ = lambda self,other: Vec(self.x-other.x,self.y-other.y)
print(v1+v2)
# using "normal" function
def add(self,other):
self.x -= other.x
self.y -= other.y
return Vec(self.x,self.y)
Vec.__add__ = add
print(v1+v2)
不適用於內置類型,例如導致TypeError: can't set attributes of built-in/extension type 'set'
另請注意,您對__add__
的實現修改了原始實例,我不喜歡這樣……(只是我的筆記)
如果您正在尋找有關如何定義 C 關卡內置函數的信息,您可能希望查看一些源代碼,請注意我專門鏈接到浮點數,但該結構適用於所有數字類型:
static PyNumberMethods float_as_number = {
float_add, /* nb_add */
float_sub, /* nb_subtract */
float_mul, /* nb_multiply */
這是實現數字方法的所有 C function 指針的結構,(在這種情況下對於浮點數)定義任何數字相關方法的每個內置類型都將定義一個PyNumberMethods
結構,然后在類型的正式定義中使用:
PyTypeObject PyFloat_Type = {
PyVarObject_HEAD_INIT(&PyType_Type, 0)
"float",
sizeof(PyFloatObject),
...
&float_as_number, /* tp_as_number */
PyTypeObject
表示在 python 中構造float
object 所需的所有相關信息(或等效的int
或str
等),其中包含所有方法、屬性和必要的元數據,以作為 python 類型工作。 因此,如果您真的想更改添加浮點數以代替執行另一個定義明確的任務,您只需將其更改為指向另一個 function:
static PyNumberMethods float_as_number = {
float_sub, /* nb_add. overrides to do subtraction because I want to break everything >:D */
float_sub, /* nb_subtract */
如果你想寫你自己的行為,你可以寫你自己的 function 並在這個結構中指向它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.