LazyCat LazyCat - 20 days ago 5x
Python Question

Class vs instance initialization in Python

I am a bit puzzled why when initializing an instance of a class in Python, I cannot use class attributes. Here is the example:

class TestClass:
... shared_list = ['a', 'b', 'c']
... def __init__(self):
... self.length = len(shared_list)


>>> TestClass.shared_list
['a', 'b', 'c']

So the list exists before any instance of the class appears, but

>>> tc = TestClass()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 4, in __init__
NameError: global name 'shared_list' is not defined

Am I missing something simple?

UPD: Thanks to everyone for help and a prompt response. I've cleared up my confusion: class doesn't define a scope in Python.


A class definition doesn't create a new scope for its methods, just a namespace for local variables. This is documented to some extent in Class Definition Syntax:

When a class definition is entered, a new namespace is created, and used as the local scope — thus, all assignments to local variables go into this new namespace. In particular, function definitions bind the name of the new function here.

When a class definition is left normally (via the end), a class object is created. This is basically a wrapper around the contents of the namespace created by the class definition.

That's why you need to reference the class attribute as TestClass.shared_list or self.shared_list in its method.