Intern
What is a getter and setter?
sobes.tech AI
Answer from AI
Getter and setter are special methods used in object-oriented programming to access and modify the values of private (or protected) class fields.
Getter:
- Provides controlled access for reading the value of a field.
- Usually has a name starting with
get(e.g.,getName()). - Can perform additional actions before returning the value (e.g., formatting or validation).
Setter:
- Provides controlled access for writing a new value to a field.
- Usually has a name starting with
set(e.g.,setName()). - Can perform validation of input data before assigning the value to the field.
- Allows implementing logic when changing the value of a field (e.g., notifying other parts of the program).
Example in Python:
class Person:
def __init__(self, name):
self._name = name # Private field
# Getter
def get_name(self):
return self._name
# Setter
def set_name(self, new_name):
if isinstance(new_name, str) and len(new_name) > 0:
self._name = new_name
else:
print("Invalid name provided")
# Usage
person = Person("Alice")
print(person.get_name()) # Using getter
person.set_name("Bob") # Using setter
print(person.get_name())
person.set_name("") # Example of setter with validation
Using getters and setters promotes encapsulation, allowing control over access and modification of data within an object, ensuring better structure and maintainability of code.