0

The Python documentation on classes says that when a class definition is entered, a new namespace is created, and used as the local scope.

Any assignments to the variables go in this local space. Function definitions bind the name of the new function in this local scope.

Then I executed this simple piece of code in Python:

class C:
    next_serial = 1337

    def __init__(self, x, y):
        self.x = x
        self.y = y
        self.z = next_serial
        next_serial += 1

c1 = C('ABC','XYZ')
print(c1.x)
print(c1.y)
print(c1.z)

It failed with UnboundLocalError: local variable 'next_serial' referenced before assignment

Now as per the documentation Class C created a new namespace which acts as a local scope where variable next_serial is bound to int object 1337 and function init is bound to the definition of the function in the class.

Why did Python not treat this local scope as an enclosing scope for the function init?

6
  • 1
    Read stackoverflow.com/questions/207000/… TLDR self.z = next_serial should be self.z = self.next_serial, same goes for next_serial += 1 Commented Feb 28, 2019 at 12:47
  • Possible duplicate of What is the difference between class and instance attributes? Commented Feb 28, 2019 at 12:47
  • I understand that next_serial is a class attribute and the exception will be resolved if this variable is qualified with self or with the class name. However my question is why doesn't Python automatically refer to the Class name space when this variable is called from inside the init method? Commented Feb 28, 2019 at 13:10
  • 1
    because that's how Python works. There's not really a better answer than that. As far as the interpreter cares, next_serial references a local variable inside __init__ that has not been defined Commented Feb 28, 2019 at 13:15
  • It's not an exact dupe, but Python nonlocal statement in a class definition might be helpful. Commented Feb 28, 2019 at 13:20

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.