Skip to content

Access Modifiers & Method Overloading

Access Modifiers

In Python, we use underscores to specify the access level of a class member.

  1. Public: Accessible from anywhere. No underscore (e.g., self.name).
  2. Protected: Should not be accessed outside the class (convention only). Single underscore (e.g., self._name).
  3. Private: Cannot be accessed or modified outside the class. Double underscore (e.g., self.__name).
class Employee:
    def __init__(self, name, salary):
        self.name = name           # Public
        self._project = "iScreen"  # Protected
        self.__salary = salary     # Private

Method Overloading

Method Overloading is the ability to create multiple methods with the same name but different parameters.

Important: Python does not support traditional method overloading (like Java or C++). If you define two methods with the same name, the last one defined will be used.

How to achieve it in Python?

We use default arguments or variable-length arguments (*args) to achieve similar behavior.

class Calculator:
    def add(self, a, b, c=0): # 'c' is optional
        return a + b + c

obj = Calculator()
print(obj.add(1, 2))    # Works (3)
print(obj.add(1, 2, 3)) # Works (6)

Method Overriding

This is different! Overriding is when a Child class changes a method already defined in the Parent class. Python supports this fully.