Jump to content

Object Oriented Programming/Getters and Setters

From Wikibooks, open books for an open world

Getters and Setters (also known as accessor and mutator methods respectively) are two types of methods used to control the access and modification of class attributes (also called properties or member variables).

Getter

[edit | edit source]

A getter method is used to retrieve the value of a private or protected class attribute. It provides read-only access to the attribute, allowing other parts of the program to retrieve its value without directly accessing the attribute. By using a getter, you can control how the attribute is accessed and apply any necessary logic or validation before returning the value.


In most programming languages, the naming convention for a getter method is to prefix it with "get," followed by the attribute name. For example, if you have a private attribute age, the corresponding getter method would typically be named getAge().

class Person:

    def __init__(self, name, age):

        self._name = name

        self._age = age

    def getAge(self):

        return self._age

# Usage

person = Person("John Doe", 25)

print(person.getAge())  # Output: 25

Setter

[edit | edit source]

A setter method is used to modify the value of a private or protected class attribute. It provides a way to update the attribute while enforcing any necessary constraints or validation rules before making the change. By using a setter, you can control how the attribute is modified and prevent any inappropriate changes.

In most programming languages, the naming convention for a setter method is to prefix it with the word "set," followed by the attribute name. For example, if you have a private attribute age, the corresponding setter method would typically be named setAge().

class Person:
    def __init__(self, name, age):
        self._name = name
        self._age = age

    def setAge(self, new_age):
        if new_age >= 0:
            self._age = new_age

# Usage
person = Person("John", 25)
person.setAge(30)
print(person.getAge())  # Output: 30

person.setAge(-5)  # The age will not be updated because of the validation in the setter method
print(person.getAge())  # Output: 30 (age remains unchanged)

See also

[edit | edit source]