My FeedDiscussionsHeadless CMS
New
Sign in
Log inSign up
Learn more about Hashnode Headless CMSHashnode Headless CMS
Collaborate seamlessly with Hashnode Headless CMS for Enterprise.
Upgrade ✨Learn more

Some Words on Python Class and NameSpace

Amineh Dadsetan's photo
Amineh Dadsetan
·Aug 15, 2019

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.

1-person_class.png

Then we initiate two instances of the class Person:

2-instantiation.png

Now, we add elements to object a.Secrets

3-adding_secrets.png

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

4-bchanges.png

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.

5-fix.png

Reference: docs.python.org/3/tutorial/classes.html