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?

  • 1
    Read https://stackoverflow.com/questions/207000/what-is-the-difference-between-class-and-instance-attributes TLDR `self.z = next_serial` should be `self.z = self.next_serial`, same goes for `next_serial += 1` – DeepSpace Feb 28 '19 at 12:47
  • Possible duplicate of [What is the difference between class and instance attributes?](https://stackoverflow.com/questions/207000/what-is-the-difference-between-class-and-instance-attributes) – DeepSpace Feb 28 '19 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? – user3610859 Feb 28 '19 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 – DeepSpace Feb 28 '19 at 13:15
  • It's not an exact dupe, but [Python nonlocal statement in a class definition](https://stackoverflow.com/questions/5466238/python-nonlocal-statement-in-a-class-definition) might be helpful. – Zero Piraeus Feb 28 '19 at 13:20
  • Brilliant. Thanks for sharing. – user3610859 Feb 28 '19 at 13:34

0 Answers0