Python 为什么我的对象显示了错误的值?
这是我的一个名为Box的简单类的代码 我想用calcVolume方法显示对象b1的体积,但它总是给我错误的答案。b1的音量是125。应该是b1。 但是,当我将返回表达式替换为我注释的表达式时,会显示正确的答案 他们不是都是同一句话,而且彼此相等吗 我尝试使用另一种替代方法,但在完成缩放功能后,我仍然得到对象b2的不正确框尺寸,请参见第二张图片Python 为什么我的对象显示了错误的值?,python,Python,这是我的一个名为Box的简单类的代码 我想用calcVolume方法显示对象b1的体积,但它总是给我错误的答案。b1的音量是125。应该是b1。 但是,当我将返回表达式替换为我注释的表达式时,会显示正确的答案 他们不是都是同一句话,而且彼此相等吗 我尝试使用另一种替代方法,但在完成缩放功能后,我仍然得到对象b2的不正确框尺寸,请参见第二张图片 在b1中的b1上调用add方法。add(b2)将b2的维度添加到b1。因此b1的维度现在与b3的维度相同。这就是为什么您的b1卷与b3卷相同的原因。您的
在
b1中的b1
上调用add方法。add(b2)
将b2的维度添加到b1。因此b1
的维度现在与b3
的维度相同。这就是为什么您的b1
卷与b3
卷相同的原因。您的问题不太清楚,但无论如何:
class Box:
count = 0
def __init__(self,l,w,d):
self.width = w
self.length = l
self.depth = d
Box.count+=1
@staticmethod
def displayBoxCount():
print ("Total box created is: %d" %Box.count)
def calcVolume(self):
return (self.width*self.length*self.depth)
def calcSurfaceArea(self):
return self.width*self.length*2+self.depth*self.width*2+2*self.length*self.depth
def scale (self,r):
self.ratio=r
self.length =self.length*self.ratio
self.width = self.width*self.ratio
self.depth =self.depth*self.ratio
return Box(self.length,self.width,self.depth)
def add(self,other):
self.width+=other.width
self.length+=other.length
self.depth+=other.depth
#return Box(self.width + other.width ,self.length +other.length ,self.depth +other.depth)
return Box(self.width,self.length,self.depth)
def __str__(self):
return "Box dimensions (Length,width depth):%0.2f,%0.2f,%0.2f"%(self.length,self.width,self.depth)
b1 = Box(2.0,3.0,2.0)
b2 = Box(3.0,2.0,3.0)
b3=b1.add(b2)
Box.displayBoxCount()
print(b3)
print(b1.calcVolume())
print(b2.calcSurfaceArea())
b2.scale(2.0)
print(b2)
他们不是都是同一句话,而且彼此相等吗
如果两个版本之间唯一的变化是使用了哪一个“return”语句,那么不,它们显然是不等价的。在第一种情况下,您更新一次“自我”维度,然后返回一个包含更新的“自我”维度的新框;在第二种情况下,您更新一次“自我”维度,然后返回一个包含第二次添加的“其他”维度的新框
请注意,在这两种情况下,您的逻辑都是有缺陷的。您希望保留“self”值,并从“self”和“other”值返回一个新的框构建,或更新“self”值,但不返回任何内容-但是从示例代码片段中,我假设您想要第一个解决方案,那么您的代码应该是:
def add(self,other):
self.width+=other.width
self.length+=other.length
self.depth+=other.depth
# return Box(self.width + other.width, self.length +other.length ,self.depth +other.depth)
return Box(self.width,self.length,self.depth)
请注意,您的scale
方法也存在类似的问题
附带说明:您希望避免在方法中硬编码类名,即:
def add(self,other):
return Box(self.width+other.width ,self.length+other.length ,self.depth +other.depth)
你想要
def __init__(self,l,w,d):
self.width = w
self.length = l
self.depth = d
Box.count+=1
@staticmethod
def displayBoxCount():
print ("Total box created is: %d" %Box.count)
但如果我使用取消注释行,它将返回正确答案??请检查更新的问题。我试过使用你的方法,但这次我弄错了比率…:(请停止发布代码图像,这些图像完全无法读取,您必须决定是希望scale方法更改当前实例还是返回一个新实例。这是一个或另一个,而不是两者的半成品混合。
def __init__(self,l,w,d):
self.width = w
self.length = l
self.depth = d
type(self).count+=1
@classmethod
def displayBoxCount(cls):
print("Total box created is: %d" % cls.count)