Python Tutorial
Python - Introduction Python - Syntax Python - Variable Python - Number Python - Casting Python - String Python - Operators Python - Conditions Python - Loops Python - List Python - Tuple Python - Set Python - Dictionary Python - Function Python - Module Python - Date & Time Python - Input Output Python - Error & Exception Python - File Handling
Python OOP
OOP - Introduction OOP - Class Members OOP - Constructor Destructor OOP - Data Hiding OOP - Inheritance OOP - Overriding OOP - Overloading

Python Data Hiding

Data hiding is one of the important features of Object Oriented Programming which allows preventing the functions of a program to access directly the internal representation of a class type.

By default all members of a class can be accessed outside of class.

You can prevent this by making class members private or protected.

In Python, we use double underscore (__) before the attributes name to make those attributes private.

We can use single underscore (_) before the attributes name to make those attributes protected.

In the above program, we tried to access hidden variable outside the class using object and it threw an exception.

We can access the value of hidden attribute by a tricky syntax as object._className__attrName:

Private methods are accessible outside their class, just not easily accessible. Nothing in Python is truly private; internally, the names of private methods and attributes are mangled and unmangled on the fly to make them seem inaccessible by their given names.



Difference between public, private and protected

Mode Description
public A public member is accessible from anywhere outside the class but within a program. You can set and get the value of public variables without any member function. By default all the members of a class would be public
private A private member variable or function cannot be accessed, or even viewed from outside the class. Only the class members can access private members. Practically, we make data private and related functions public so that they can be called from outside of the class
protected A protected member is very similar to a private member but it provided one additional benefit that they can be accessed in sub classes which are called derived/child classes.

You will learn parent-child relationship of classes in the next chapter.


Printing Objects

Printing objects gives us information about objects we are working with.

In C++, we can do this by adding a friend ostream& operator << (ostream&, const Foobar&) method for the class.

In Java, we use toString() method.

In python this can be achieved by using __repr__ or __str__ methods.

Important Points about Printing Object:

If __repr__ and __str__ methods are not defined then: