Initializing an instance of a vs class in Python

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.

+4
source share
3 answers
Definition

A classdoes not create a new scope for its methods, just a namespace for local variables. This is somewhat documented in the Class Definition Syntax :

, - , . , .

( ), . , .

TestClass.shared_list self.shared_list .

+3

__init__, TestClass.

__init__ shared_list, . , :

def __init__(self):
    self.length = len(TestClass.shared_list)

, :

def __init__(self):
    self.not_shared_list = ['a', 'b', 'c']
    self.length = len(self.not_shared_list)
+2

If you did not specify the "environment" of the variable shared_list, here it is selfor TestClass, python considers it to be a global variable that is neither defined nor defined.

Use self.shared_listor TestClass.shared_listto link to it.

+1
source

Source: https://habr.com/ru/post/1656375/


All Articles