Sobes.tech
Junior — Middle

How is a private parameter declared and used in an object-oriented programming language?

sobes.tech AI

Answer from AI

In Python, private parameters (attributes) in classes are declared using a double underscore at the beginning of the name, for example __param. This triggers the name mangling mechanism, which changes the attribute's name, making it less accessible from outside.

Example:

class MyClass:
    def __init__(self):
        self.__private_param = 42  # private parameter

    def get_private_param(self):
        return self.__private_param

obj = MyClass()
print(obj.get_private_param())  # 42
# print(obj.__private_param)  # will raise AttributeError

Although direct access to __private_param from outside is not possible, it can be accessed via the name _MyClass__private_param, but this is considered bad practice. This approach helps encapsulate data and protect it from accidental modification from outside.