Definition
A method that returns the value of an object’s attribute.
Characteristics
- Used in object-oriented programming
- Provides read-only access to an attribute without exposing the attribute directly
- Usually named with the
get_prefix, e.g.get_name() - Supports encapsulation by providing controlled access to hidden data
- Typically returns the value of a private attribute
- Often paired with a setter
- May include logic (e.g., formatting or deriving a value) before returning the attribute
- Usually public
- Does not modify the value of the attribute before returning it
Examples
class Student:
# constructor
def __init__(self, p_name, p_id):
self.name = p_name
self.__id = p_id
# getter
def get_id(self):
return self.__idNon-examples
- Directly accessing a public attribute, e.g.,
print(student.name)