Public Protected and Private Attributes and Methods
Python uses naming conventions - rather than strict enforced rules - to indicate how accessible a class's attributes and methods are meant to be from outside the class.
Public Members
Public attributes and methods have no leading underscore and can be accessed freely from anywhere, both inside and outside the class.
class Student:
def __init__(self, name):
self.name = name # public attribute
s = Student("Abhay")
print(s.name) # accessible directly
Protected Members
A single leading underscore (_attribute) signals that an attribute is intended for internal use within the class or its subclasses. It's a convention, not a strict restriction - Python still allows outside access, but it's a signal to other developers not to.
class Student:
def __init__(self, name):
self._roll_number = "internal use"
Private Members
A double leading underscore (__attribute) triggers name mangling, where Python internally renames the attribute to make it harder (though not impossible) to access from outside the class, offering the closest thing Python has to true privacy.
class Account:
def __init__(self, balance):
self.__balance = balance # private attribute
def get_balance(self):
return self.__balance
acc = Account(1000)
print(acc.get_balance()) # 1000 - accessed via a public method
Coming Up Next
Next, you'll learn the difference between class variables and instance variables, and when to use each.