有没有办法可以添加两个 class 的实例?
Is there a way to be able to add two instances of a class?
class Fraction:
def __init__(self, n, d):
self.n = n
self.d = d
def __str__(self):
return "{}/{}".format(self.n, self.d)
像这样。我想实现不同的运算符,但我不知道该怎么做。
这段代码应该有帮助:
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
class Fraction:
def __init__(self, n, d):
self.n = n
self.d = d
def __str__(self):
return "{}/{}".format(self.n, self.d)
像这样。我想实现不同的运算符,但我不知道该怎么做。
这段代码应该有帮助:
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