Public, protected, and private methods ​in Python

Did you know?

Python doesn't have public, protected, or private methods.

Instead, use the following naming conventions:

  1. method_name -> public
  2. _method_name -> protected
  3. __method_name -> private

The same goes for attributes.

An example👇

class User:
    def __init__(self, first_name, last_name, age):
        self.first_name = first_name
        self.last_name = last_name
        self.__age = age

    def age(self):
        return "You shouldn't ask that. It's a private information."

    def _is_adult(self):
        return self.__age >= 21

    def can_drink_alcohol(self):
        return self._is_adult()