分配前引用的局部变量'周长'?

时间:2015-08-27 01:29:19

标签: python class error-handling

我正在教自己如何在Python上学习课程,并且我在这方面感到困惑。这是代码:

import random

class Rectangle:
    def __init__(self, length, width):
        self.length = length
        self.width = width
        length = random.randint(1,25)
        width = random.randint(25,50)

    def calc_area(self):

        area = length * width

        return area
    def calc_perimeter(self):

        perimeter = (length * 2) + (perimeter * 2)
        return perimeter

#main

length = random.randint(1,25)
width = random.randint(25,50)
rect = Rectangle(length,width)
area = float(rect.calc_area())
perimeter = float(rect.calc_perimeter())


print("The area of the rectangle is %.2f and the perimeter is %.2f " %(area,perimeter))

每次运行程序时都会出现此错误:

Traceback (most recent call last):
  File "/Volumes/CS DRIVE/Sample Text for Python/buusheee.py", line 28, in <module>
    perimeter = float(rect.calc_perimeter())
  File "/Volumes/CS DRIVE/Sample Text for Python/buusheee.py", line 19, in calc_perimeter
    perimeter = (length * 2) + (perimeter * 2)
UnboundLocalError: local variable 'perimeter' referenced before assignment

我不确定“Perimeter”的错误是什么,因为我使用相同的代码格式来获取该区域并且它没有给我任何问题。只有在包含周边时才会出现错误。如果消除周边并且只离开该区域,它就会运行。任何帮助,将不胜感激。

2 个答案:

答案 0 :(得分:2)

以下行失败,因为您在定义之前尝试在右侧使用perimeter -

perimeter = (length * 2) + (perimeter * 2)

我真的不认为你想在那里使用外围。我相信你想在那里使用width(因为那将是矩形周长的正确公式),因为 -

perimeter = (length * 2) + (width * 2)

此外,当您访问lengthwidth时,您正在访问全局变量,而应该访问self.lengthself.width,以便您访问该特定内容实例的长度和宽度 -

perimeter = (self.length * 2) + (self.width * 2)

您的calc_area()方法也有类似的更改。

答案 1 :(得分:0)

您还应该使用方法中的widthheight来访问Rectangle实例的self.widthself.height属性。考虑:

import random

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

    def calc_area(self):

        area = self.length * self.width
        return area

    def calc_perimeter(self):

        perimeter = (self.length * 2) + (self.width * 2)
        return perimeter

#main

length = random.randint(1,25)
width = random.randint(25,50)
rect = Rectangle(length,width)
area = float(rect.calc_area())
perimeter = float(rect.calc_perimeter())

print("The area of the rectangle is %.2f and the perimeter is %.2f " %(area,perimeter))