Object Oriented Programming in Python | Set 2 (Data Hiding and Object Printing)

07 Jun, 2022
Prerequisite: Object-Oriented Programming in Python | Set 1 (Class, Object and Members)
 Data hiding 
In Python, we use double underscore (Or __) before the attributes name and those attributes will not be directly visible outside. 
Python
class MyClass:      # Hidden member of MyClass    __hiddenVariable = 0        # A member method that changes     # __hiddenVariable     def add(self, increment):        self.__hiddenVariable += increment        print (self.__hiddenVariable)   # Driver codemyObject = MyClass()     myObject.add(2)myObject.add(5)  # This line causes errorprint (myObject.__hiddenVariable)
Output : 
2
7
Traceback (most recent call last):
  File "filename.py", line 13, in 
    print (myObject.__hiddenVariable)
AttributeError: MyClass instance has 
no attribute '__hiddenVariable' 
In the above program, we tried to access a hidden variable outside the class using an object and it threw an exception.We can access the value of a hidden attribute by a tricky syntax: 
Python
# A Python program to demonstrate that hidden# members can be accessed outside a classclass MyClass:      # Hidden member of MyClass    __hiddenVariable = 10  # Driver codemyObject = MyClass()     print(myObject._MyClass__hiddenVariable)
Output : 
10
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 [See this for source ]. 
 Printing Objects 
Printing objects give 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.
Python
class Test:    def __init__(self, a, b):        self.a = a        self.b = b      def __repr__(self):        return "Test a:%s b:%s" % (self.a, self.b)      def __str__(self):        return "From str method of Test: a is %s," \              "b is %s" % (self.a, self.b)  # Driver Code        t = Test(1234, 5678)print(t) # This calls __str__()print([t]) # This calls __repr__()
Output : 
From str method of Test: a is 1234,b is 5678
[Test a:1234 b:5678]
Important Points about Printing: 
If no __str__ method is defined, print t (or print str(t)) uses __repr__. 
Python
class Test:    def __init__(self, a, b):        self.a = a        self.b = b      def __repr__(self):        return "Test a:%s b:%s" % (self.a, self.b)  # Driver Code        t = Test(1234, 5678)print(t) 
Output :
Test a:1234 b:5678
If no __repr__ method is defined then the default is used. 
Python
class Test:    def __init__(self, a, b):        self.a = a        self.b = b  # Driver Code        t = Test(1234, 5678)print(t) 
Output :
<__main__.Test instance at 0x7fa079da6710> 
Python Programming Tutorial | Object Oriented Programming in Python - Part 2 | GeeksforGeeks - YouTubeGeeksforGeeks530K subscribersPython Programming Tutorial | Object Oriented Programming in Python - Part 2 | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:58•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=bmySfHUAuU4" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
sg4ipiafwot258z3lh6xa2mjq2qtxd89f49zgt7g
Python
School Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
Python Dictionary
Reverse a string in Java
Arrays in C/C++
Introduction To PYTHON
Interfaces in Java