Bird
Raised Fist0
Pythonprogramming~10 mins

Getter and setter methods in Python - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Concept Flow - Getter and setter methods
Create object with private attribute
Call getter method
Return attribute value
Call setter method
Update attribute value
Call getter method again
Return updated value
This flow shows how an object with private data uses getter to read and setter to update the value safely.
Execution Sample
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

p = Person('Alice')
print(p.get_name())
p.set_name('Bob')
print(p.get_name())
This code creates a Person with a private name, reads it, changes it, then reads the new name.
Execution Table
StepActionVariable/MethodValue/ResultOutput
1Create Person objectp._name'Alice'
2Call get_name()p.get_name()'Alice'Alice
3Call set_name('Bob')p._name'Bob'
4Call get_name() againp.get_name()'Bob'Bob
5End of programExecution stops
💡 Program ends after printing updated name 'Bob'
Variable Tracker
VariableStartAfter Step 1After Step 3Final
p._nameundefined'Alice''Bob''Bob'
Key Moments - 3 Insights
Why do we use get_name() instead of accessing p._name directly?
Using get_name() allows controlled access to the private variable _name, as shown in step 2 of the execution_table, which helps protect the data.
What happens if we call set_name() with a new value?
As seen in step 3, set_name() updates the private variable _name safely, changing it from 'Alice' to 'Bob'.
Why is the variable named _name with an underscore?
The underscore signals that _name is meant to be private and should not be accessed directly, encouraging use of getter and setter methods.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of p._name after step 3?
A'Bob'
B'Alice'
Cundefined
DNone
💡 Hint
Check the 'Variable/Method' and 'Value/Result' columns at step 3 in the execution_table.
At which step does the program print 'Alice'?
AStep 1
BStep 3
CStep 2
DStep 4
💡 Hint
Look at the 'Output' column in the execution_table for when 'Alice' is printed.
If we remove the set_name method call, what will be printed at step 4?
A'Bob'
B'Alice'
CError
DNone
💡 Hint
Refer to variable_tracker to see if p._name changes without set_name call.
Concept Snapshot
Getter and setter methods control access to private data.
Use get_name() to read and set_name() to update.
Private variables use underscore prefix (_name).
This protects data and allows validation.
Call getters and setters instead of direct access.
Full Transcript
This lesson shows how getter and setter methods work in Python. We create a class Person with a private variable _name. The get_name method returns the current name, and set_name updates it. We trace the program creating a Person named Alice, printing the name, changing it to Bob, and printing again. The execution table shows each step and variable changes. Key moments explain why we use getters and setters and the meaning of the underscore. The quiz asks about variable values and outputs at different steps. The snapshot summarizes how getters and setters protect and manage private data.

Practice

(1/5)
1. What is the main purpose of getter and setter methods in a Python class?
easy
A. To create new classes dynamically
B. To control access to private attributes safely
C. To execute code asynchronously
D. To delete objects from memory

Solution

  1. Step 1: Understand getter and setter roles

    Getter methods retrieve attribute values, and setter methods update them while controlling access.
  2. Step 2: Identify their purpose in encapsulation

    They protect private data by allowing controlled reading and writing, preventing direct access.
  3. Final Answer:

    To control access to private attributes safely -> Option B
  4. Quick 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
A. @property.setter\ndef set_age(self, value):\n self._age = value
B. @setter.age\ndef age(self, value):\n self._age = value
C. @age.setter\ndef age(self, value):\n self._age = value
D. @age.setter\ndef set_age(self):\n self._age = value

Solution

  1. Step 1: Recall setter syntax with @property

    The setter uses @attribute.setter decorator and method name matches the attribute.
  2. Step 2: Check method signature

    Setter method takes self and value parameters to set the attribute.
  3. Final Answer:

    @age.setter\ndef age(self, value):\n self._age = value -> Option C
  4. Quick 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
A. bob
B. Error
C. alice
D. BOB

Solution

  1. Step 1: Understand setter behavior

    Setter converts the assigned value to uppercase before storing it.
  2. Step 2: Trace code execution

    Initially name is 'alice', then set to 'bob' which setter changes to 'BOB'. Printing returns 'BOB'.
  3. Final Answer:

    BOB -> Option D
  4. Quick 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
A. Setter method missing value parameter
B. Getter method missing return statement
C. Property decorator used incorrectly
D. No error, code runs fine

Solution

  1. Step 1: Check setter method signature

    Setter must accept two parameters: self and value to set the attribute.
  2. Step 2: Identify missing parameter

    Current setter only has self, missing value parameter, causing error on assignment.
  3. Final Answer:

    Setter method missing value parameter -> Option A
  4. Quick 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
A. 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
B. class Temperature: def __init__(self, fahrenheit=32): self._fahrenheit = fahrenheit @property def celsius(self): return (self._fahrenheit - 32) * 5/9 @celsius.setter def celsius(self, value): self._fahrenheit = (value * 9/5) + 32
C. 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
D. class Temperature: def __init__(self, fahrenheit=32): self.fahrenheit = fahrenheit @property def celsius(self): return (self.fahrenheit - 32) * 5/9 @celsius.setter def celsius(self, value): self.fahrenheit = (value * 9/5) + 32

Solution

  1. Step 1: Understand internal storage and interface

    The class stores temperature internally in Celsius (_celsius) but exposes Fahrenheit via getter and setter.
  2. Step 2: Check getter and setter calculations

    Getter converts Celsius to Fahrenheit; setter converts Fahrenheit to Celsius and stores it.
  3. 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.
  4. Final Answer:

    Option A code correctly implements the behavior -> Option A
  5. Quick 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