Python:print语句在下半部分找不到值,打印方法绑定了吗?

时间:2015-03-31 01:40:12

标签: python class object

我试图创建一个矩形对象,它取高度和宽度并计算周长和面积。似乎第一个矩形能够计算面积和周长,但第二个矩形只是说它无法找到高度或宽度,或者我需要返回的任何其他值。此外,当打印第一个矩形时,它会打印一个“方法绑定”的东西,而不是函数的实际值:

   class Rectangle:
def __init__(self,height=2, width=2):
    self.height = (height)
    self.width = (width)



def setHeight(height):
    if type(height)!=int:
        height = 2
    else:
        height = height
def setWidth(width):
    if type(width)!=int:
        width = 2
    else:
        width = width

def getHeight():
    return height
def getWidth():
    return width


def perimeter(self):
    perimeter = ((2*height)+(2*width))
    return perimeter


def area(self):
    area = (height * width)
    return area

def getStats(self):
    print("Width: {}".format(width))
    print("Height: {}".format(height))
    print("Area: {}".format(area))
    print("Perimeter: {}".format(perimeter))

def main():
    print ("Rectangle a:")
    a = Rectangle(5,7)
    print ("area:      {}".format(a.area()))
    print ("perimeter: {}".format(a.perimeter()))
    print ("")
    print ("Rectangle b:")
    b = Rectangle()
    b.width = 10
    b.height = 20
    print (b.getStats())

main()

2 个答案:

答案 0 :(得分:1)

您的代码有几个问题,例如在引用实例属性时省略self,在引用函数或定义类时省略调用(()),将__init__命名为{{ 1}},并且格式/缩进不正确。以下代码修复了这些错误,似乎可以正常工作。

init

结果:

class Rectangle():
    def __init__(self,height=2, width=2):
        self.height = height
        self.width = width
    def setHeight(self, height):
        if type(height)!=int:
            self.height = 2
        else:
            self.height = height
    def setWidth(self, width):
        if type(width)!=int:
            self.width = 2
        else:
            self.width = width

    def getHeight(self):
        return self.height
    def getWidth(self):
        return self.width

    def perimeter(self):
        perimeter = ((2*self.height)+(2*self.width))
        return perimeter

    def area(self):
        return self.height * self.width

    def getStats(self):
        print("Width: {}".format(self.width))
        print("Height: {}".format(self.height))
        print("Area: {}".format(self.area()))
        print("Perimeter: {}".format(self.perimeter()))

def main():
    print ("Rectangle a:")
    a = Rectangle(5,7)
    print ("area: {}".format(a.area()))
    print ("perimeter: {}".format(a.perimeter()))
    print ()
    print ("Rectangle b:")
    b = Rectangle()
    b.width = 10
    b.height = 20
    b.getStats()

main()

答案 1 :(得分:0)

任何特定于类实例的方法都应该作为输入传入self。例如:

def setHeight(self, height):
    if type(height)!=int:
        self.height = 2
    else:
        self.height = height

我相信您遇到的问题是您尝试使用b.width访问矩形“b”的属性。由于您没有将self传递给方法,因此height和width变量并不特定于Rectangle类的任何一个实例。此外,您应该避免直接访问属性。因此,不要使用b.width=10,而是使用b.setWidth(10)