寻求帮助以解决此问题,我认为问题在于第7行将两个值相加。不幸的是,我没有很多运气解决这个问题。任何帮助,将不胜感激。
谢谢。
class Apple:
def __init__(self, number_of_seeds):
self.number_of_seeds = number_of_seeds
green_apple = Apple(number_of_seeds=10)
red_apple = Apple(number_of_seeds=20)
print(f'{green_apple + red_apple}')
您不能只将两个Apple
实例加在一起,因为这没有定义,但是您可以将Apple.number_of_seeds
加在一起,因为这只是整数加法。例如:
class Apple:
def __init__(self, number_of_seeds):
self.number_of_seeds = number_of_seeds
green_apple = Apple(number_of_seeds=10)
red_apple = Apple(number_of_seeds=20)
print (red_apple.number_of_seeds + green_apple.number_of_seeds)
# 30
或者,您可以定义打印方法(__str__
或__repr__
)和__add__
方法,但是实现起来有点先进:
class Apple:
def __init__(self, number_of_seeds):
self.number_of_seeds = number_of_seeds
def __add__(self, other_apple):
self.number_of_seeds += other_apple.number_of_seeds
return self.number_of_seeds
def __repr__(self):
return str(self.number_of_seeds)
green_apple = Apple(number_of_seeds=10)
red_apple = Apple(number_of_seeds=20)
print(f'{green_apple + red_apple}')
# 30
尝试一下:
green_apple=Apple(10)
red_apple=Apple(20)