Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Public variables in Python classes?

I am learning Python classes on my own right now and came across this page:

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

The variable empCount is a class variable whose value would be shared among all instances of a this class. This can be accessed as Employee.empCount from inside the class or outside the class.

I'm assuming 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 like self.var (declared in the init or something) vs. a public variable like this?

like image 380
John Smith Avatar asked May 12 '13 17:05

John Smith


2 Answers

It is called a class attribute. Python doesn't distinguish between public and private; privacy is only indicated by convention, and is not enforced.

It is technically good practice if you need to share data among instances. Remember, methods are class attributes too!

like image 119
Martijn Pieters Avatar answered Sep 29 '22 13:09

Martijn Pieters


The difference is, if the variable is declared inside the __init__ constructor, the variable stands different for different class variables. (i.e) If there are two objects for the class, each have a different memory space for this variable. If it is declared like this empcount, the same memory space is shared or accessed by all the objects of the class. In this case, each object created increases the value of empcount by 1. So when a variable is to be shared by all objects , use this kind of static declaration. But change to this variable affects all the objects of the class.

like image 26
Aswin Murugesh Avatar answered Sep 29 '22 11:09

Aswin Murugesh