The Wayback Machine - https://web.archive.org/web/20240823071213/https://www.geeksforgeeks.org/object-oriented-programming-in-python-set-2-data-hiding-and-object-printing/
Open In App

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

Last Updated : 07 Jun, 2022
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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 code
myObject = MyClass()     
myObject.add(2)
myObject.add(5)
  
# This line causes error
print (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 class
class MyClass:
  
    # Hidden member of MyClass
    __hiddenVariable = 10
  
# Driver code
myObject = 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> 



Similar Reads

Data Hiding in Python
In this article, we will discuss data hiding in Python, starting from data hiding in general to data hiding in Python, along with the advantages and disadvantages of using data hiding in python. What is Data Hiding? Data hiding is a concept which underlines the hiding of data or information from the user. It is one of the key aspects of Object-Orie
3 min read
8 Tips For Object-Oriented Programming in Python
OOP or Object-Oriented Programming is a programming paradigm that organizes software design around data or objects and relies on the concept of classes and objects, rather than functions and logic. Object-oriented programming ensures code reusability and prevents Redundancy, and hence has become very popular even in the fields outside software engi
6 min read
Introduction of Object Oriented Programming
As the name suggests, Object-Oriented Programming or OOPs refers to languages that use objects in programming. Object-oriented programming aims to implement real-world entities like inheritance, hiding, polymorphism, etc in programming. The main aim of OOP is to bind together the data and the functions that operate on them so that no other part of
6 min read
Hiding and encrypting passwords in Python?
There are various Python modules that are used to hide the user’s inputted password, among them one is maskpass() module. In Python with the help of maskpass() module and base64() module we can hide the password of users with asterisk(*) during input time and then with the help of base64() module it can be encrypted. maskpass() maskpass() is a Pyth
6 min read
Python PyQt5 - Hiding the Progress Bar ?
In this article we will see how to hide the progress bar in PyQt5 application. There two ways in which we can hide the progress - Using hide method.Setting visibility status of progress bar to False. Method #1 : With the help of hide method, we can hide the progress bar. Below is the implementation. C/C++ Code # importing libraries from PyQt5.QtWid
2 min read
PyQt5 - Hiding the radio button
In this article we will see how we can hide the radio button, when we create a GUI(Graphical User Interface) we creates radio button but when their uses get complete there is a need to make these radio button hide so that user cant make them check or uncheck any more. In order to do to this we have to do the following: 1. Create radio button 2. Cre
2 min read
PyQt5 QSpinBox – Hiding the spin box
In this article we will see how we can hide the spin box, while making GUI(Graphical User Interface) when the use of widget get completed there is a need to remove the widget from the screen in order to do this we can hide the spin box. In order to do this we will use hide() method. Syntax : spin_box.hide() Argument : It takes no argument Return :
2 min read
PyQt5 QSpinBox – Hiding it using setHidden method
In this article we will see how we can make the spin box hidden with the help of sethidden method. We can hide the spin box using hide method as well but setHidden method takes bool as argument which determine whether it should hide the spin box or not when called. In order to do so we use setHidden method. Syntax : spin_box.setHidden(bool) Argumen
2 min read
PyQt5 QCalendarWidget - Hiding according to the user
In this article we will see how we can hide the QCalendarWidget according to the user, hiding is exactly opposite of showing the QCalendarWidget. Calendar widget is a big widget therefore there is need to hide it when user don't need it. In order to do this we will use hide method with the QCalendarWidget object.Syntax : calendar.hide()Argument : I
2 min read
PyQt5 QCalendarWidget - Hiding the Navigation Bar
In this article we will see how we can hide the navigation bar of the QCalendarWidget. Navigation bar is the top section of the calendar which is used to change the next month, previous month, month selection, year selection. By default navigation bar is visible although we can hide it any time, below is the representation of navigation bar of QCal
1 min read
Python | Matplotlib Graph plotting using object oriented API
In object-oriented API, first, we create a canvas on which we have to plot the graph and then we plot the graph. Many people prefer object-oriented API because it is easy to use as compared to functional API. Let's try to understand this with some examples. Example #1: # importing matplotlib library import matplotlib.pyplot as plt # x axis values x
2 min read
Object oriented testing in Python
Prerequisite: Object-Oriented Testing Automated Object-Oriented Testing can be performed in Python using Pytest testing tool. In this article, we perform object-oriented testing by executing test cases for classes. We write a program that has one parent class called Product and three child classes - Snack, Beverage, and Staples. We implement all th
5 min read
Printing Lists as Tabular Data in Python
During the presentation of data, the question arises as to why the data has to be presented in the form of a table. Tabular data refers to the data that is stored in the form of rows and columns i.e., in the form of a table. It is often preferred to store data in tabular form as data appears more organized and systematic. We are going to illustrate
6 min read
Multi-Line printing in Python
We have already seen the basic use of print function previous article. Now, let's see how to use print function for multi-line printing. This can easily be done using multiline string i.e. three single quotes ''' Geeksforgeeks ''' . Let's see different examples to see the demonstration for the same. Example #1: # basic example for multi-line printi
1 min read
Python | Printing list vertically
Printing the list has been dealt many times. But sometimes we need a different format to get the output of list. This also has application in getting a transpose of matrix. Printing list vertically also has application in web development. Lets discuss certain ways in which this task can be achieved. Method #1 : Using Naive Method The naive method c
5 min read
Pretty Printing XML in Python
XML stands for Extensible Markup Language and is used to encode a document that can be understandable by both humans and machines. Data stored in XML format is easy to understand and easy to modify. There are three main things that have to keep in mind when you are using XML – Simplicity, Generality, and Usability. Pretty Printing XML using xml.dom
2 min read
Programs for printing pyramid patterns in Python
Exploring and creating pyramid patterns in Python is an excellent way to enhance your programming skills and gain a deeper understanding of loops and control structures. By modifying and experimenting with the provided examples, you can create a variety of captivating patterns using Python. Exploring Pyramid Patterns in PythonPyramid patterns are s
9 min read
Printing pattern with Recursion using Python Turtle
Pre-requisites: Turtle Programming in Python In this article, we are going to display the following pattern using Python Turtle with recursion. In this pattern, the first circle should start with 100-pixel radius, and each subsequent circle is 5 pixels smaller until it reaches radius 10 when the last circle is indrawn. The first circle is drawn wit
2 min read
Printing Triangle Pattern in Java
Given a number N, the task is to print the following pattern:- Examples: Input : 10 Output : * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Input :5 Output : * * * * * * * * * * * * * * * There is a nested loop required to print the above pattern. The outer loop is used to run for the n
3 min read
Printing HELLO with turtle module
Turtle is a Python Module which allows us to draw a various geometrical illustration by just importing it in Python and using the inbuilt function of the turtle Module. We can use functions like turtle.forward(â€Ķ) and turtle.right(â€Ķ) which can move the turtle around. Turtle is a beginner-friendly way to learn python by running some basic commands an
3 min read
Pretty-Printing in BeautifulSoup
Prerequisite: requestsBeautifulSoup In this article, we will learn about how to print pretty in BeautifulSoup Using Python. The requests library is an integral part of Python for making HTTP requests to a specified URL. Whether it be REST APIs or Web Scraping, requests are must be learned for proceeding further with these technologies. When one mak
2 min read
Printing triangle star pattern using a single loop
Given a number N, the task is to print the star pattern in single loop. Examples:  Input: N = 9Output: * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Input: N = 5Output: * * * * * * * * * * * * * * * Please Refer article for printing the pattern in two loops as:Triangle pattern in Java Approach 1:Approach:
10 min read
Pattern Printing question asked in CGI Coding Round
Write a program that receives a number as input and prints it in the following format as shown below. Examples : Input : n = 3 Output : 1*2*3*10*11*12 --4*5*8*9 ----6*7 Input : n = 4 Output : 1*2*3*4*17*18*19*20 --5*6*7*14*15*16 ----8*9*12*13 ------10*11 Asked in CGI coding round Approach: The approach is to see the problem, not as a single task bu
15+ min read
How to suppress scientific notation when printing float values?
Scientific notation, also known as exponential notation, is a way of expressing numbers that are too large or too small to be conveniently written in decimal form. While useful in many scientific and engineering contexts, it can be cumbersome when you need to display float values in a more readable format without exponent notation. What is Scientif
2 min read
Learn Programming Languages- List of 11 Popular Programming Languages
In this rapidly growing world, programming languages are also rapidly expanding, and it is very hard to determine the exact number of programming languages. It is an essential part of software development because it creates a communication bridge between humans and computers. Now, if you are a beginner who wants to learn, search the internet, you w
9 min read
Convert JSON data Into a Custom Python Object
Let us see how to convert JSON data into a custom object in Python. Converting JSON data into a custom python object is also known as decoding or deserializing JSON data. To decode JSON data we can make use of the json.loads(), json.load() method and the object_hook parameter. The object_hook parameter is used so that, when we execute json.loads(),
2 min read
Data type Object (dtype) in NumPy Python
Every ndarray has an associated data type (dtype) object. This data type object (dtype) informs us about the layout of the array. This means it gives us information about: Type of the data (integer, float, Python object, etc.)Size of the data (number of bytes)The byte order of the data (little-endian or big-endian)If the data type is a sub-array, w
3 min read
OOP in Python | Set 3 (Inheritance, examples of object, issubclass and super)
We have discussed following topics on Object Oriented Programming in Python Object Oriented Programming in Python | set-1 Object Oriented Programming in Python | Set 2 (Data Hiding and Object Printing) In this article, Inheritance is introduced. One of the major advantages of Object Oriented Programming is re-use. Inheritance is one of the mechanis
4 min read
Python Pandas - Convert PeriodIndex object to Timestamp and set the frequency
In this article, we will discuss how to convert period index objects to timestamp and set the frequency in the python programming language. The pandas PeriodIndex.to_timestamp() method is used to convert a PeriodIndex object to Timestamp and set the frequency. frequency can be set using the 'freq' parameter of the method. Example 1: Pandas package
3 min read
Stringio And Bytesio For Managing Data As File Object
StringIO and BytesIO are classes provided by the io module in Python. They allow you to treat strings and bytes respectively as file-like objects. This can be useful when you want to work with in-memory file-like objects without actually writing to or reading from physical files. In this article, we will see how we can use StringIO And BytesIO For
5 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg