Python 過載乘法運算子

2021-09-19 08:42:49 字數 732 閱讀 1197

python 中的乘法運算子就是計算標量積(scalar product),也叫元素級乘法 (elementwise multipication)

如下:

def __mul__(self, scalar):

if isinstance(scalar, numbers.real):

return vector(n * scalar for n in self)

else:

return notimplemented

def __rmul__(self, scalar):

return self * scalar

涉及 vector 運算元的積還有一種,叫兩個向量的點積(dot product),如果把乙個向量看做 1xn 矩陣,把另乙個向量看做 nx1 矩陣,那麼就是矩陣乘法。在 numpy 中,點積使用 numpy.dot()函式計算。

如下:

def __matmul__(self, other):

try:

return sum(a * b for a, b in zip(self, other))

except typeerror:

return notimplemented

def __rmatmul__(self, other):

return self @ other # this only works in python 3.5

Python 運算子過載

在 python 中is 是兩個運算子,對物件進行比較,分別對id,type value 進行比較。is 比較id type value三維 而 僅 比較value。實驗發現其實is,僅僅是比較一些簡單的基礎變數。class test object def init self self.value ...

Python運算子過載

print 呼叫父類建構函式 def parentmethod self print 呼叫父類方法 def setattr self,attr self.parentattr attr def getattr self print 父類屬性 self.parentattr def del self ...

python 運算子過載

運算子過載就是讓用類寫成的物件,可截獲並響應用在內建型別上的運算 加法,切片,列印和點號運算等 1.以雙下劃線命名的方法 x 的特殊鉤子,python運算子過載的實現是提供特殊命名的方法來攔截運算,python替每種運算和特殊命名的方法之間,定義了固定不變的對映關係 2.當例項出現在內建運算時,這類...