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
When manually implementing getters and setters in Python, the following naming conventions are commonly used:
-
A
getterthat returns a class attribute is named in the formatget_attributeName. -
A
setterthat sets or modifies a class attribute is named in the formatset_attributeName.
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.
Which of the following methods is used to set or modify a class's attribute value?
get_attributeName
print_attributeName
set_attributeName
remove_attributeName
Lecture
AI Tutor
Design
Upload
Notes
Favorites
Help
Code Editor
Execution Result