0

我是 Python 新手,在运行这个 Python 类时遇到这些错误:

我正在使用 PyScripter,并且正在运行 Python 3.9(64 位)

我创建了 Heater 类,初始化了一个变量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
4

1 回答 1

1

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

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

于 2020-11-25T21:49:45.773 回答