By default all methods and attributes in a python class are public. That means They can be accessed by the class members and by the module which contains it’s import. There is no inbuilt syntax available for private, protected, friend, protected friend attribute in python, but you can do necessary changes to your variables to achieve the same.
The main concept behind not having any of those logic is because, We used to have those access specifiers so that out side classes will not be able to use the attribute of a class. But unless the developer will not try to access a class within another class, They are not going to be used like that. So default is public anyone can access any method anywhere.
But, You can privatize them in a different and more logical way. Using _ or __ .
Use of __:
__ can be used to define private attributes in a class. by default we define all variable names as words, but if you define a class member starting with __ it becomes private and it can not be accessed directly. Python defines it’s magic functions as __ at start as well as at the end. eg, __init__ but for private attributes of a class the name should be mangled as __ only at the beginning of the name of the variable. Now once it is done you can not access the variable directly from it’s object. You can not change the value directly. Let me show you all with example.
>>> class A(object): .... name = 'class name' .... __name1 = 'class name 1' .... >>> a = A() >>> a.name class name >>> a.__name1 --------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-4-5d5520ef9fe0> in <module>() ----> 1 a.__name AttributeError: 'A' object has no attribute '__name' >>> a._A__name1 class name 1 >>> a._A__name1 = 'new edited value' >>> a._A__name1 new edited value >>> b = A() >>> b._A__name1 class name 1
This is how __ works. The variable prefixed with __ almost becomes invisible to everyone and can not be accessed out side of the class object.
Use of _:
Adding _ at the start of the variable name doesn’t change much with the functionality. The variable can still be accessed out side of the class and from the object as well. also from the module that contains it’s import.
But if the variable name is mangled with _ It becomes unique in a way so that if you do
from module import *
It’s value remains the same that is defined inside of the class and not overridden by other variables in the next module with the same name.
Using these you can actually limit access to many things in your development. I hope this will make your life easier 🙂