Python入门程序员

问题描述 投票:-2回答:2

寻求帮助以解决此问题,我认为问题在于第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}')
python python-3.7
2个回答
0
投票

您不能只将两个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

-1
投票

尝试一下:

green_apple=Apple(10)
red_apple=Apple(20)
© www.soinside.com 2019 - 2024. All rights reserved.