Skip to content

Instantly share code, notes, and snippets.

@rksys
Created May 28, 2016 08:27
Show Gist options
  • Save rksys/3a41a2e5451e548143a809a32ea4a7f9 to your computer and use it in GitHub Desktop.
Save rksys/3a41a2e5451e548143a809a32ea4a7f9 to your computer and use it in GitHub Desktop.
def __truedive__(self,fraction):
if fraction.numerator == 0:
print('Cannot divide by 0')
exit()
else:
return(Fraction(self.numerator*fraction.denominator,self.denominator*fraction.numerator))
@rksys
Copy link
Author

rksys commented May 28, 2016

学生的出错信息:

a = Fraction(1,2)
>>> b = Fraction(3,4)
>>> a / b
Traceback (most recent call last):
  File "<pyshell#12>", line 1, in <module>
    a / b
TypeError: unsupported operand type(s) for /: 'Fraction' and 'Fraction'

@rksys
Copy link
Author

rksys commented May 28, 2016

给学生的回答

你的"魔法方法名错了", 应该用__truediv__.

魔法方法名错误的结果就是, python解释器在运行 a/b的时候, 操作符/会找不到对应的魔法方法.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment