How to Create a Python Getter Function?

Estimated read time 2 min read

In Python, a getter function is a method that allows you to retrieve the value of a private instance variable of a class. Here’s an example of how to create a getter function in Python:

class MyClass:
    def __init__(self):
        self.__my_private_variable = "Hello, World!"
    def get_my_private_variable(self):
        return self.__my_private_variable

In this example, we define a class called MyClass that contains a private instance variable called __my_private_variable.

To create a getter function for this variable, we define a method called get_my_private_variable(). This method returns the value of the private instance variable by calling self.__my_private_variable.

Note that the private instance variable is accessed using the double underscore prefix (__). This makes the variable inaccessible from outside the class, but it can still be accessed from within the class using the getter function.

Here’s an example of how to use the getter function to retrieve the value of the private instance variable:

my_object = MyClass()
my_variable = my_object.get_my_private_variable()
print(my_variable)  # Output: "Hello, World!"

In this example, we create an instance of the MyClass class called my_object. We then call the get_my_private_variable() method on this object to retrieve the value of the private instance variable.

The resulting value is stored in the variable my_variable and printed to the console.

Note that using getter functions is a common practice in Python programming to enforce encapsulation and maintain data integrity in classes.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply