Combining Getters & Setters



Getters

Getters are a concept in object-oriented programming that allow you to retrieve the value of an attribute from a class instance. They provide controlled access to the class data and allow you to perform additional logic when getting the attribute value. In Python, you can implement getters using the @property decorator.

Here's a detailed explanation of getters along with a simple example:

Getter Methods:

  1. Getters are methods that act as accessors for class attributes. They return the value of an attribute but allow you to apply custom logic before returning the value.
  2. In Python, you can create a getter method using the @property decorator before the method definition. This decorator tells Python that the method is a getter for a specific attribute.
  3. The getter method must have the same name as the attribute it is getting. For example, to get the attribute x, the getter method should be named x as well.
  4. You can use getters to make sure that you always get a valid and up-to-date value for an attribute, especially if the value depends on other attributes or requires computation.

Main Difference b/w Using @property

For this example

class Example:

    def __init__(self, thing) -> None:
        self.thing = thing

    def get_thing(self):
        return self.thing

    @property
    def thing(self):
        return self.thing

to get the value form get_thing(), you call it like

obj = Example(5)
print(obj.get_thing()) # prints: 5

but with using @property, you would call the other method like