10

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?

1
  • It is simply called class attribute.They are equivalent to c++'s static data members. Commented May 12, 2013 at 17:47

2 Answers 2

8

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!

Sign up to request clarification or add additional context in comments.

2 Comments

So if my program was all about connecting to a remote API and pulling in data, would it make sense to store the URL as a "class attribute" or as a self.URL variable (sorry I don't know what you call these)
Instance attributes - no, not really. Use class attributes as defaults (setting the same name on the instance masks the class attribute), for state that needs to be shared among all instances, or data you need to alter when creating new instances (like a counter to generate unique ids per instance).
2

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.

3 Comments

So even though many objects may be instantiated and empcount=0 in the class, it only gets initialized to 0 the first time the class is instantiated (and then increased by 1 via init)?
yes. Whenever the constructor is called, the empcount value is increased by one, thus the empcount value gives the number of objects the class has..
As said, this is equivalent the initialization of static variables in c

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.