0
0
Pythonprogramming~5 mins

Getter and setter methods in Python

Choose your learning style9 modes available
Introduction

Getter and setter methods let you safely read and change values inside an object. They help keep data correct and private.

When you want to control how a value is read or changed in an object.
When you want to check or change data before saving it.
When you want to hide the details of how data is stored inside an object.
When you want to add extra actions when a value changes, like updating another value.
When you want to prevent direct access to important data to avoid mistakes.
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
Simple getter and setter for a person's name.
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
Setter checks if temperature is above absolute zero before setting.
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)
OutputSuccess
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.