Skip to main content
Practice

Managing Object Attributes with Getters and Setters

In a class, getter and setter methods are used to access or modify the attributes of an object indirectly.

A getter is used to read a property's value, while a setter is used to set or modify a property's value.

In Python, you can implement getters and setters directly or use the @property decorator to achieve the same functionality.


Implementing Without Decorators

Typically, when implementing getters and setters directly in Python, the following conventions are adhered to:

  • A getter that returns a class attribute is named in the format get_attributeName.

  • A setter that sets or modifies a class attribute is named in the format set_attributeName.

Example Usage of Getters and Setters
class Person:
def __init__(self, name):
# Private variable
self.__name = name

def get_name(self):
return self.__name

def set_name(self, value):
# Check if value is a string
if isinstance(value, str):
self.__name = value
else:
raise ValueError("Name must be a string.")

person = Person("John")
print(person.get_name())
# Outputs 'John'

person.set_name("Mike")
# Changes name to 'Mike'
print(person.get_name())
# Outputs 'Mike'

# Attempt to set an invalid value (will raise an error)
# person.set_name(123)

In the code above, the get_name method of the Person class returns the __name attribute, and the set_name method sets the value of __name.

The set_name method checks whether the value is a string, and if not, it raises a ValueError.

By implementing getters and setters, you gain control over attribute access and can ensure safe modification of attribute values.

In the next lesson, we'll learn how to implement getters and setters using the @property decorator.

Want to learn more?

Join CodeFriends Plus membership or enroll in a course to start your journey.