[英]Operator Overloading in Python coming from C++
我正在嘗試重載代表數學分數的Python類中的某些運算符。 特別是我正在嘗試重載*運算符,以便可以進行分數*分數,分數*整數和整數*分數運算。 我對C ++有一定的經驗,在那種情況下,我會像在Fraction類中那樣編寫運算符重載:
friend Fraction operator*(const Fraction &f1, const Fraction &f2);
friend Fraction operator*(const Fraction &f, int v);
friend Fraction operator*(int v, const Fraction &f);
我的理解是C ++根據您提供的參數知道要解析的函數。 但是,由於在Python中未鍵入函數參數,我對Python如何知道要解析的運算符重載感到困惑。 例如:
def __mul__(self, other):
return Fraction(self.numerator * other.numerator, self.denominator * other.denominator)
def __mul__(self,value):
return Fraction(self.numerator * value,self.denominator)
第一個重載將適用於兩個分數,第二個重載將適用於分數和整數,但是Python如何知道要使用哪個? 盡管我已經使用C ++一段時間了,但我對Python還是完全陌生的。
Python根本不會按類型解析函數。 首先只能使用一種名為__mul__
方法 。 該方法的多個版本具有不同的簽名。 如有必要,您將必須在該方法內手動進行類型解析:
def __mul__(self, other):
if isinstance(other, int):
...
請注意,盡可能多地使用鴨子類型是pythonic,所以您可能要檢查hasattr(other, 'numerator')
而不是嚴格的isinstance
檢查。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.