Getter and setter methods let you safely read and change values inside an object. They help keep data correct and private.
Getter and setter methods in Python
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Syntax
Python
class ClassName: def __init__(self, value): self._attribute = value def get_attribute(self): return self._attribute def set_attribute(self, new_value): self._attribute = new_value
Use a single underscore (_) before attribute names to show they are 'private' by convention.
Getter methods start with get_ and setter methods start with set_.
Examples
Python
class Person: def __init__(self, name): self._name = name def get_name(self): return self._name def set_name(self, new_name): self._name = new_name
Python
class Temperature: def __init__(self, celsius): self._celsius = celsius def get_celsius(self): return self._celsius def set_celsius(self, temp): if temp < -273.15: print('Temperature too low!') else: self._celsius = temp
Sample Program
This program creates a bank account with a balance. It uses getter and setter to read and update the balance safely. It prevents setting a negative balance.
Python
class BankAccount: def __init__(self, balance): self._balance = balance def get_balance(self): return self._balance def set_balance(self, amount): if amount < 0: print('Cannot set negative balance!') else: self._balance = amount account = BankAccount(100) print('Initial balance:', account.get_balance()) account.set_balance(150) print('Updated balance:', account.get_balance()) account.set_balance(-50)
Important Notes
Getter and setter methods help protect data inside objects.
Python also has a built-in @property decorator to create getters and setters more easily.
Summary
Getter methods read values safely from an object.
Setter methods update values with checks or extra steps.
They help keep data private and correct inside objects.
Practice
1. What is the main purpose of getter and setter methods in a Python class?
easy
Solution
Step 1: Understand getter and setter roles
Getter methods retrieve attribute values, and setter methods update them while controlling access.Step 2: Identify their purpose in encapsulation
They protect private data by allowing controlled reading and writing, preventing direct access.Final Answer:
To control access to private attributes safely -> Option BQuick Check:
Getter/setter = control private data [OK]
Hint: Getters and setters manage private data access [OK]
Common Mistakes:
- Thinking they create new classes
- Confusing with asynchronous code
- Assuming they delete objects
2. Which of the following is the correct syntax to define a setter method for attribute
age using the @property decorator in Python?easy
Solution
Step 1: Recall setter syntax with @property
The setter uses@attribute.setterdecorator and method name matches the attribute.Step 2: Check method signature
Setter method takesselfandvalueparameters to set the attribute.Final Answer:
@age.setter\ndef age(self, value):\n self._age = value -> Option CQuick Check:
Setter uses @age.setter and method age(self, value) [OK]
Hint: Setter uses @attribute.setter and method named attribute [OK]
Common Mistakes:
- Using wrong decorator like @setter.age
- Method name not matching attribute
- Setter missing value parameter
3. What will be the output of the following code?
class Person:
def __init__(self, name):
self._name = name
@property
def name(self):
return self._name
@name.setter
def name(self, value):
self._name = value.upper()
p = Person('alice')
p.name = 'bob'
print(p.name)medium
Solution
Step 1: Understand setter behavior
Setter converts the assigned value to uppercase before storing it.Step 2: Trace code execution
Initially name is 'alice', then set to 'bob' which setter changes to 'BOB'. Printing returns 'BOB'.Final Answer:
BOB -> Option DQuick Check:
Setter uppercases value, output = BOB [OK]
Hint: Setter modifies value before storing, output reflects change [OK]
Common Mistakes:
- Expecting original lowercase 'bob'
- Thinking print shows initial 'alice'
- Assuming code raises error
4. Identify the error in this code snippet using getter and setter methods:
class Car:
def __init__(self):
self._speed = 0
@property
def speed(self):
return self._speed
@speed.setter
def speed(self):
self._speed = 100
c = Car()
c.speed = 50
print(c.speed)medium
Solution
Step 1: Check setter method signature
Setter must accept two parameters: self and value to set the attribute.Step 2: Identify missing parameter
Current setter only has self, missing value parameter, causing error on assignment.Final Answer:
Setter method missing value parameter -> Option AQuick Check:
Setter needs (self, value) parameters [OK]
Hint: Setter must have value parameter besides self [OK]
Common Mistakes:
- Omitting value parameter in setter
- Confusing getter and setter decorators
- Assuming code runs without error
5. You want to create a class
Temperature that stores temperature in Celsius internally but allows getting and setting the temperature in Fahrenheit using getter and setter methods. Which code correctly implements this behavior?hard
Solution
Step 1: Understand internal storage and interface
The class stores temperature internally in Celsius (_celsius) but exposes Fahrenheit via getter and setter.Step 2: Check getter and setter calculations
Getter converts Celsius to Fahrenheit; setter converts Fahrenheit to Celsius and stores it.Step 3: Verify correct use of private attribute and decorators
class Temperature: def __init__(self, celsius=0): self._celsius = celsius @property def fahrenheit(self): return (self._celsius * 9/5) + 32 @fahrenheit.setter def fahrenheit(self, value): self._celsius = (value - 32) * 5/9 uses _celsius internally and @property/@fahrenheit.setter correctly.Final Answer:
Option A code correctly implements the behavior -> Option AQuick Check:
Internal Celsius, getter/setter convert Fahrenheit [OK]
Hint: Store Celsius internally, convert in getter/setter for Fahrenheit [OK]
Common Mistakes:
- Storing Fahrenheit internally instead of Celsius
- Using public attributes without underscore
- Mixing getter/setter names and attributes
