Python 3.x Python类方法中如何增加实例变量
我陷入了这个问题(第二部分)。问题如下: 创建一个名为AppleBasket的类,该类的构造函数接受两个输入:一个表示颜色的字符串和一个表示苹果数量的数字。构造函数应该初始化两个实例变量:apple\u color和apple\u quantity。编写一个名为increase的类方法,每次调用它时将数量增加1。您还应该为此类编写一个str方法,该方法返回一个字符串格式:“一篮[数量到这里][颜色到这里]苹果。”例如,“一篮4个红苹果”或“一篮50个蓝苹果” 我的代码是:Python 3.x Python类方法中如何增加实例变量,python-3.x,class-method,Python 3.x,Class Method,我陷入了这个问题(第二部分)。问题如下: 创建一个名为AppleBasket的类,该类的构造函数接受两个输入:一个表示颜色的字符串和一个表示苹果数量的数字。构造函数应该初始化两个实例变量:apple\u color和apple\u quantity。编写一个名为increase的类方法,每次调用它时将数量增加1。您还应该为此类编写一个str方法,该方法返回一个字符串格式:“一篮[数量到这里][颜色到这里]苹果。”例如,“一篮4个红苹果”或“一篮50个蓝苹果” 我的代码是: class Apple
class AppleBasket():
def __init__(self, apple_color, apple_quantity):
self.apple_color = apple_color
self.apple_quantity = apple_quantity
def getC(self):
return self.apple_color
def getQ(self):
return self.apple_quantity
def __str__(self):
return "A basket of {} {} apples.".format(self.apple_quantity, self.apple_color)
def increase(self):
return self.apple_quantity + 1
print(AppleBasket("Red", 4))
然而,数量仍然保持在4而不是5
请告诉我我犯了什么错误?谢谢。纠正您的增加方法:
def增加(自身):
self.apple_数量+=1
类应用程序密钥:
definit(自身、苹果颜色、苹果数量):
self.apple\u color=apple\u color
self.apple\u数量=apple\u数量
def ap(self):
self.apple_color=apple_color
def apl(self):
self.apple_quantity=apple_quantity
def __str__(self):
return "A basket of {} {} apples.".format(self.apple_quantity,self.apple_color)
def increase(self):
self.apple_quantity += 1
打印(AppleBasket(“绿色”,4))您没有将该值设置为5,只是返回一个添加的1。尝试一下self.apple\u quantity+=1就行了。非常感谢。我真傻,竟然错过了。谢谢,成功了。但是,为什么必须删除该返回语句:如果我写return self.apple_quantity+=1,它会给出语法错误。这里有点困惑。你需要想想实际发生了什么<代码>+=是一个加法赋值运算符。实现相同结果的另一种方法是
self.apple\u quantity=self.apple\u quantity+1
,这显然不能作为返回值。在我们的理解中还有更多。谢谢。为什么这反映了“每次调用时数量增加1”<代码>def增加(自身):
self.apple\u数量+=1
class AppleBasket():
def ___init__(self, color, quantity):
self.apple_color = color
self.apple_quantity = quantity
def increase(self):
self.apple_quantity += 1
def __str__(self):
return "A basket of {} {} apples.".format(self.apple_quantity, self.apple_color)