class Fraction:
def __init__(self, n, d):
self.n = n
self.d = d
def __str__(self):
return "{}/{}".format(self.n, self.d)
像这样。我想实现其他运算符,但是我不知道该怎么办。
答案 0 :(得分:1)
此代码应提供帮助:
class A:
def __init__(self, a):
self.a = a
def __add__(self, other):
"""Addition operation"""
return A(self.a + other.a)
def __sub__(self, other):
"""Subtraction operation"""
return A(self.a - other.a)
x = A(10) + A(8) # x.a == 18
x = A(10) - A(8) # x.a == 2