Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Class as Decorator in Python
Next article icon

Private Attributes in a Python Class

Last Updated : 21 Feb, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In Python, encapsulation is a key principle of object-oriented programming (OOP), allowing you to restrict access to certain attributes or methods within a class. Private attributes are one way to implement encapsulation by making variables accessible only within the class itself. In this article, we will explore how to create private attributes in a Python class.

Private Attributes in a Class in Python

Below are some of the examples by which we can understand about how we can create a private attribute in a class in Python:

Using Double Underscore Prefix

In this example, we have an id attribute of a class and we want to make the attribute private. So for making the attribute private, we can use (__).

Python3
# Creating a Class class Student:     name = "Lokesh Singh"      __id = 1234            # Method for Printing Private Attribute     def Print_Id(self):         print(f"The Id of student is : {self.__id}")      lokesh = Student() print(f"The name of student is : {lokesh.name}") # Public Attribute can be accessed directly from outside class  # Accessing private attribute using getter method lokesh.Print_Id()      

Output
The name of student is : Lokesh Singh The Id of student is : 1234

Using Double Underscore Prefix with getter-setter method

In this example, we have defined a constructor that will set the data of student and a getter method to get the private data of the student as the private member cannot be accessed directly from outside the class.

Python3
class Student:     def __init__(self, name, id):         self.__id = id         self.name = name      def get_Id(self):         return self.__id  # Setting the data of the student sonali = Student("Sonali Kumari", 58)  # Printing the name as the name is public print("The name is :", sonali.name)  # Printing the Id by getter method as the id is private print("The id is :", sonali.get_Id()) 

Output
The name is : Sonali Kumari The id is : 58

Using Property Decorator

In this example, we have used Property Decorator method to get the data. we have a constructor consisting of a private data and a method that will print the private data. As we know that private members of the class cannot be accesses outside the class.

Python3
class Private:     def __init__(self):         self.__private_attr = 10      @property     def Get_Private_Data(self):         return self.__private_attr  obj = Private() print("The Private Data is :", obj.Get_Private_Data) 

Output
The Private Data is : 10

Next Article
Class as Decorator in Python

O

officialsi8v5f
Improve
Article Tags :
  • Python
  • Python Programs
  • python-basics
  • python-oop-concepts
Practice Tags :
  • python

Similar Reads

  • Built-In Class Attributes In Python
    Python offers many tools and features to simplify software development. Built-in class attributes are the key features that enable developers to provide important information about classes and their models. These objects act as hidden gems in the Python language, providing insight into the structure
    4 min read
  • AttributeError: can’t set attribute in Python
    In this article, we will how to fix Attributeerror: Can'T Set Attribute in Python through examples, and we will also explore potential approaches to resolve this issue. What is AttributeError: can’t set attribute in Python?AttributeError: can’t set attribute in Python typically occurs when we try to
    3 min read
  • Class as Decorator in Python
    While function-based decorators are widely used, class-based decorators can offer more flexibility and better organization, especially when the decorator needs to maintain state or requires multiple methods to function properly. A Python class decorator is simply a class that implements the __call__
    3 min read
  • How to Change Class Attributes By Reference in Python
    We have the problem of how to change class attributes by reference in Python, we will see in this article how can we change the class attributes by reference in Python. What is Class Attributes?Class attributes are typically defined outside of any method within a class and are shared among all insta
    3 min read
  • AttributeError: __enter__ Exception in Python
    One such error that developers may encounter is the "AttributeError: enter." This error often arises in the context of using Python's context managers, which are employed with the with statement to handle resources effectively. In this article, we will see what is Python AttributeError: __enter__ in
    4 min read
  • How To Make a Subclass from a Super Class In Python
    In Python, you can create a subclass from a superclass using the class keyword, and by specifying the superclass in parentheses after the subclass name. The subclass inherits attributes and behaviors from the superclass, allowing you to extend or modify its functionality while reusing the existing c
    3 min read
  • Python Class Members
    Python, similarly to other object-oriented allows the user to write short and beautiful code by enabling the developer to define classes to create objects. The developer can define the prototype of an object class based on two types of members: Instance membersClass members In the real world, these
    6 min read
  • How to Import Other Python Files?
    We have a task of how to import other Python Files. In this article, we will see how to import other Python Files. Python's modular and reusable nature is one of its strengths, allowing developers to organize their code into separate files and modules. Importing files in Python enables you to reuse
    3 min read
  • Multilevel Inheritance in Python
    Python is one of the most popular and widely used Programming Languages. Python is an Object Oriented Programming language which means it has features like Inheritance, Encapsulation, Polymorphism, and Abstraction. In this article, we are going to learn about Multilevel Inheritance in Python. Pre-Re
    3 min read
  • Python Program to Get the Class Name of an Instance
    In this article, we will see How To Get a Class Name of a class instance. For getting the class name of an instance, we have the following 4 methods that are listed below: Using the combination of the __class__ and __name__ to get the type or class of the Object/Instance.Use the type() function and
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences