Python 为什么这个代码会打印28?

Python 为什么这个代码会打印28?,python,class,oop,Python,Class,Oop,此代码打印28作为答案。我试图理解背景中发生了什么,但无法理解。我恳请你,如果可以的话,请解释一下 class Geom(object): def __init__(self, h=10, w=10): self.h, self.w =h,w def rectangle(self): rect = self.h*2+self.w*2 return rect a = Geom(4) print(a.rectangle()) >>28 a、 h=4,a.w=10

此代码打印28作为答案。我试图理解背景中发生了什么,但无法理解。我恳请你,如果可以的话,请解释一下

class Geom(object):
def __init__(self, h=10, w=10):
    self.h, self.w =h,w
def rectangle(self):
    rect = self.h*2+self.w*2
    return rect
a = Geom(4)
print(a.rectangle())
>>28
a、 h=4,a.w=10默认值

rect=4*2+10*2=28

a=Geom4将对象a的属性h设置为4,w设置为10


调用对象a上的矩形返回self.h*2+self.w*2,即4*2+10*2,即28。

此处,您已将构造函数初始化为a=Geom4,这意味着高度h设置为4。由于没有指定w的初始值,因此默认值为10

那么,什么时候排队

rect = self.h*2+self.w*2
在调用矩形方法时,其计算如下

rect = 4*2 + 10*2
结果是答案28

a.h为4;a、 w是10。把每一个乘以2,再加起来,得到28。看起来没那么复杂。