Private attributes help keep some parts of an object hidden so others can't change them by mistake.
0
0
Private attributes in Python
Introduction
When you want to protect important data inside an object from being changed directly.
When you want to control how data inside an object is accessed or modified.
When you want to hide details that users of your class don't need to see.
When you want to avoid accidental changes to internal variables.
When you want to make your code safer and easier to maintain.
Syntax
Python
class ClassName: def __init__(self): self.__private_attribute = None
Private attributes start with two underscores __.
This makes Python change the name internally to avoid easy access from outside.
Examples
This creates a private attribute
__speed inside the Car class.Python
class Car: def __init__(self, speed): self.__speed = speed
Private attribute
__name is accessed safely using a method get_name.Python
class Person: def __init__(self, name): self.__name = name def get_name(self): return self.__name
Sample Program
This program shows a private attribute __balance in a BankAccount class. It can only be changed by methods inside the class. Trying to access it directly causes an error.
Python
class BankAccount: def __init__(self, balance): self.__balance = balance # private attribute def deposit(self, amount): if amount > 0: self.__balance += amount def get_balance(self): return self.__balance account = BankAccount(100) print(account.get_balance()) # prints 100 account.deposit(50) print(account.get_balance()) # prints 150 # Trying to access private attribute directly try: print(account.__balance) except AttributeError as e: print(e)
OutputSuccess
Important Notes
Private attributes are not truly hidden but renamed internally (name mangling).
You can still access them using _ClassName__attribute but it is not recommended.
Use private attributes to protect important data and keep your code clean.
Summary
Private attributes start with two underscores __ to hide them.
They help protect data inside objects from outside changes.
Access private attributes using methods inside the class.