Search code examples
pythonpython-3.xclasslocalunbound

UnboundLocalError: local variable 'temperature' referenced before assignment in the member function after creating a constructor?


I am new in Python and I get these errors when running this Python class:

I am using PyScripter and I am running Python 3.9 (64-bit)

I created the class Heater, initialized a variable temperature, and some functions that modifies this variable.

Then I created an object and used the functions then it gave me an Error!

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()

I am getting the following Output and then this Error:

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

I changed temperature = 0 into nonlocal temperature then I get this error:

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

Solution

  • After looking at your code, I noticed that you are trying to access self.temperature using just temperature.

    The first argument each method receives (self) is a reference of the object itself, and is used to access object attributes and methods.