add a getter to a class in python

To add a getter to a class in Python, you can create a method within the class that returns the value of an attribute. This method should have the @property decorator. Here is an example code snippet:

main.py
class MyClass:
    def __init__(self, attribute):
        self._attribute = attribute

    @property
    def attribute(self):
        return self._attribute
157 chars
8 lines

In this code, MyClass has an attribute named _attribute. The getter method attribute returns the value of _attribute. Using the @property decorator allows you to access this method like an attribute, without needing to call it like a function. You can also add additional logic or conditions to the getter method if needed. This is a helpful technique for encapsulating the attributes of a class and controlling access to them.

gistlibby LogSnag