I am a bit puzzled why when initializing an instance of a class in Python, I cannot use class attributes. Here is the example:
... shared_list = ['a', 'b', 'c']
... def __init__(self):
... self.length = len(shared_list)
['a', 'b', 'c']
>>> 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
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
self.shared_list in its method.