Why this code does print 28?

时间:2018-06-20 05:04:36

标签: python class oop

This code prints 28 as an answer. I try to understand what's going on in the background, but cannot figure it out. I kindly ask, If you can, please explain.

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

4 个答案:

答案 0 :(得分:1)

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

所以,当行

rect = self.h*2+self.w*2
rectangle()方法中

被调用,其计算方式为

rect = 4*2 + 10*2

得出答案28

答案 1 :(得分:0)

a.h = 4,a.w = 10个默认值;

rect = 4 * 2 + 10 * 2 = 28

答案 2 :(得分:0)

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

在对象 a 上调用rectangle()会返回self.h * 2 + self.w * 2,即 28 。{p}

答案 3 :(得分:-1)

如评论所述,您的self.h仍未分配给该值。

通过将2个参数传递到init函数中,可以正确分配h和w。

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,4)
相关问题