UnboundLocalError:在创建构造函数后,在成员函数中赋值之前引用了局部变量“temperature”?

2024-06-01 13:12:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我是Python新手,在运行此Python类时遇到以下错误:

我使用的是PyScripter,运行的是Python 3.9(64位)

我创建了类加热器,初始化了一个变量temperature,以及一些修改这个变量的函数

然后我创建了一个对象并使用了函数,然后它给了我一个错误

class Heater :
    temperature  = 0

    def __init__(self):
        temperature = 20

    def warmer(self):
        temperature += 5

    def cooler(self):
        temperature -= 5

    def display(self):
        print ("Temperature is " , self.temperature)

h1 = Heater()

h1.display()
h1.cooler()
h1.display()
h1.warmer()
h1.display()

我得到以下输出,然后出现此错误:

Temperature is  0
Traceback (most recent call last):
  File "<module1>", line 30, in <module>
  File "<module1>", line 22, in cooler
UnboundLocalError: local variable 'temperature' referenced before assignment

我将temperature = 0更改为nonlocal temperature,然后出现以下错误:

  File "<module1>", line 13
SyntaxError: no binding for nonlocal 'temperature' found

Tags: 函数selfisdef错误displaylineh1
1条回答
网友
1楼 · 发布于 2024-06-01 13:12:12

查看代码后,我注意到您正试图使用temperature访问self.temperature

每个方法接收的第一个参数(self)是对象本身的引用,用于访问对象属性和方法

相关问题 更多 >