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:
@property
decorator before the method definition. This decorator tells Python that the method is a getter for a specific attribute.x
, the getter method should be named x
as well.@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