call a getter on an instance of a class in python

To call a getter method on an instance of a class in Python, you first need to define the class with the getter method. Here's an example class with a getter method named "get_name":

main.py
class Person:
    def __init__(self, name):
        self._name = name
        
    def get_name(self):
        return self._name
129 chars
7 lines

To call the "get_name" method on an instance of the "Person" class, you would first create an instance of the class, like this:

main.py
person = Person("John")
24 chars
2 lines

Then, you can call the getter method on the instance using the dot notation:

main.py
name = person.get_name()
print(name)  # Output: John
53 chars
3 lines

In this example, the "get_name" method returns the value of the private attribute "name" of the instance. The "" before the attribute name is used to indicate that the attribute is intended to be private, and should not be accessed directly from outside the class. Instead, a getter method is used to provide controlled access to this attribute.

gistlibby LogSnag