我正在尝试重载Python类中的一些操作符,它表示一个数学部分。特别是,我试图重载*操作符,这样就可以进行分数*分数、分数*整数和整数*分数运算。我对C++有过一些经验,在这种情况下,我会编写操作符重载,如分数类中的那样:
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完全陌生。
发布于 2017-07-25 10:46:37
Python根本不会按类型解析函数。首先只能有一个名为__mul__的方法,而不是具有不同签名的该方法的多个版本。如果有必要,您必须在该方法中手动进行类型解析:
def __mul__(self, other):
if isinstance(other, int):
...请注意,尽可能多地使用鸭子类型是pythonic的,所以您可能希望检查hasattr(other, 'numerator')而不是严格的isinstance检查。
https://stackoverflow.com/questions/45300957
复制相似问题