Sobes.tech
Junior — Middle

What are the features of inheritance and encapsulation in object-oriented programming in Python?

sobes.tech AI

Answer from AI

In Python, inheritance and encapsulation have their own features:

Inheritance:

  • Python supports multiple inheritance, meaning a class can inherit from several base classes.
  • To call methods of the base class, the super() function is used.

Encapsulation:

  • Python does not have strict privacy, but there are conventions:
    • Attributes and methods starting with a single underscore _ are considered protected and not intended for external use.
    • Attributes with double underscores __ trigger name mangling, which makes external access more difficult but does not make them fully private.

Example:

class Base:
    def __init__(self):
        self._protected = "protected"
        self.__private = "private"

    def get_private(self):
        return self.__private

class Child(Base):
    def show(self):
        print(self._protected)  # accessible
        # print(self.__private)  # will cause an error
        print(self.get_private())  # access through method

c = Child()
c.show()

Thus, encapsulation in Python is more based on conventions rather than strict restrictions.