Start a personal dev blog on your domain for free with Hashnode and grow your readership.
Get Started

Some Words on Python Class and NameSpace

Python classes are different from the classes in C or Java in some quirky ways. Here, I set out to explain one difference. We create a class called Person, with a class variable of type list.


Then we initiate two instances of the class Person:


Now, we add elements to object a.Secrets


The unexpected result here is that by changing a.secrets, b.secrets has also changed.


Now, this happens because the list Secrets, is a class variable and a class variable is shared between all of the instances of that class.

why is the reason for this? It's because of concept of Namespacing.

Once, the class definition is past, a class object is created, which is actually a wrapper around all of the variables in the namespace associated to that class.

Note that this class object is for the class itself and not the instances of that class. Also, note that class variables is different form the variables of instances of that class.

Now, when we instantiate a and b, it actually is assignment. Now in the assignment a = Person( 'Bob' ), it bound the name a to the the class object for Person. Also in the assignment b = Person( 'David' ), name b is bound to the same class object person as in the previous assinment.

Now, assigning name a and name b to the same class object, would cause both a and b share the same variable Secrets, and thus changing a.Secrets means changing b.Secrets.

All of this would be solved if the Secrets was an instance variable rather than a class variable. Here, we can see a usage of keyword 'self'. in fact a.self.Secrets would not be shared between a and b because it is an instance variable rather than a class variable.



Start a personal dev blog on your domain for free and grow your readership.

3.4K+ developers have started their personal blogs on Hashnode in the last one month.

Write in Markdown · Publish articles on custom domain · Gain readership on day zero · Automatic GitHub backup and more

No Comments Yet