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 formatget_attributeName
. -
A
setter
that 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 directly, you gain control over attribute access and can safely set 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
Guidelines
AI Tutor
Publish
Design
Upload
Notes
Favorites
Help
Code Editor
Execution Result