Public vs Private attributes
In Python, attributes are like variables that belong to an object. When you create a class and then an object from it, the object can have attributes (data) attached to it. For example:
class Person:
def __init__(self, name, age):
self.name = name # Attribute
self.age = age # Attribute
# Create an object
person = Person("Alice", 25)
print(person.name) # Output: Alice
print(person.age) # Output: 25
andname are attributes.age
- We accessed them directly using
andperson.name
.person.age
By default, Python makes all attributes public.
What are public attributes?
A public attribute can be:
- Accessed (read or changed) directly from anywhere in the program.
- It’s open to everyone.
Example:
class Car:
def __init__(self, brand, speed):
self.brand = brand # Public attribute
self.speed = speed # Public attribute
# Create an object
car = Car("Toyota", 120)
# Access and modify public attributes
print(car.brand) # Output: Toyota
car.speed = 150 # Modify the speed
print(car.speed) # Output: 150
What are private attributes?
A private attribute is meant to be used only inside the class. It’s hidden from outside access. Python doesn’t enforce strict privacy but provides a way to indicate an attribute is private by using
Why use private attributes?
- To protect data from being accidentally changed or misused.
- To follow the principle of encapsulation (hiding details from the outside world).
How to make an attribute private?
-
Using a Single Underscore
:_
- This is a convention to say, “Hey, this attribute is internal! Don’t touch it from outside the class.”
- It’s still accessible if you really want, but it’s a signal for developers.
Example:
class BankAccount: def __init__(self, balance): self._balance = balance # Private attribute (by convention) def get_balance(self): return self._balance account = BankAccount(1000) print(account.get_balance()) # Output: 1000 # Accessing _balance directly (not recommended) print(account._balance) # Output: 1000
-
Using a Double Underscore
:__
- This is a stronger way to protect an attribute.
- Python “mangles” the attribute name so it’s harder to access it from outside the class.
Example:
class BankAccount: def __init__(self, balance): self.__balance = balance # Strongly private def get_balance(self): return self.__balance account = BankAccount(1000) print(account.get_balance()) # Output: 1000 # Trying to access __balance directly will fail # print(account.__balance) # AttributeError
Python internally changes the name of
balance to something like__
. This makes it harder to access accidentally._BankAccount__balance
If you really need to access it:
print(account._BankAccount__balance) # Output: 1000
When to use public vs private attributes?
Type | Use Case | Access |
---|---|---|
Public | Data that’s safe to be accessed by anyone |
|
Private _ |
Data meant to be accessed only by the class (but not strictly enforced) |
|
Private __ |
Critical data you want to protect more strictly |
|
Real-world example: protecting Bank data
Imagine a bank account class where we want to ensure no one can directly modify the balance.
class BankAccount:
def __init__(self, balance):
self.__balance = balance # Private attribute
def deposit(self, amount):
if amount > 0:
self.__balance += amount
else:
print("Invalid deposit amount!")
def withdraw(self, amount):
if 0 < amount <= self.__balance:
self.__balance -= amount
else:
print("Invalid withdrawal amount!")
def get_balance(self):
return self.__balance
# Create an account
account = BankAccount(1000)
# Use methods to interact with private data
account.deposit(500)
print(account.get_balance()) # Output: 1500
account.withdraw(200)
print(account.get_balance()) # Output: 1300
# Direct access is blocked
# print(account.__balance) # AttributeError
Key points to remember:
-
Public Attributes:
- Open and accessible to everyone.
- Use for data that’s safe to read or modify from outside the class.
-
Private Attributes:
- Use
(convention) for less critical data you don’t want accidentally accessed._
- Use
for stricter protection of important data.__
- Use
-
Encapsulation:
- By keeping sensitive data private, you control how it’s accessed and modified, ensuring safety.