Public variables in Python classes?

I am learning Python classes myself and came across this page:

http://www.tutorialspoint.com/python/python_classes_objects.htm

The empCount variable is a class variable whose value will be shared between all instances of this class. You can do this with Employee.empCount from the class or outside the class.

I assume this is called a public variable? Or a static public variable?

Is this technically good practice? I know this question is a bit soft, but generally speaking, when is it better to have a class variable such as self.var (declared in init or something else) versus a public variable?

+6
source share
2 answers

It is called a class attribute. Python makes no distinction between public and private; confidentiality is indicated only by agreement and does not apply.

This is technically good practice if you need to exchange data between instances. Remember that methods are also class attributes!

+5
source

The difference is that if a variable is declared inside the __init__ constructor, the variable is different for different class variables. (ie) If a class has two objects, each of them has a different memory space for this variable. If it is declared as empcount , then the same memory space will be shared or available for all objects of the class. In this case, each created object increases the value of empcount by 1. Therefore, when a variable should be used by all objects, use this type of static declaration. But changing this variable affects all objects in the class.

+1
source

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


All Articles