I am a little puzzled why when initializing an instance of a class in Python I cannot use class attributes. Here is an example:
class TestClass:
... shared_list = ['a', 'b', 'c']
... def __init__(self):
... self.length = len(shared_list)
Now
>>> TestClass.shared_list
['a', 'b', 'c']
So, the list exists until 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: Thank you all for your help and quick response. I cleared my confusion: the class does not define scope in Python.
source
share