OOP & classes
Classes, instances, methods, dataclasses, and object-oriented design in Python.
Add property getter setter validation in Python
Shows how to use @property with a setter to validate values before assigning them in a Python class.
class Temperature:
def __init__(self, celsius=0):
self._celsius = celsius # Use underscore to avoid recursion
@property
def celsius(self):
"""Getter returns the stored value."""
return self._celsius
@celsius.setter
def celsius(self, value):
"""Setter valid…
Borg pattern shared state in Python
Implement the Borg pattern to share state across class instances by assigning a class-level dictionary to each instance's __dict__.
class Borg:
_shared_state = {}
def __init__(self):
self.__dict__ = Borg._shared_state
class ConfigManager(Borg):
def __init__(self):
super().__init__()
if not hasattr(self, "settings"):
self.settings = {}
def set(self, key, value):
self.settings[key] = va…
Browse by section
Each section groups closely related Python snippets.
OOP & classes — Python code examples
What you will find here
This page collects oop & classes snippets — short, copy-ready Python you can paste into our free online IDE and run without installing anything. Each sample includes a plain-English explanation and the full source code.
Samples vs tutorials and challenges
Samples are quick reference — one concept per page. For step-by-step teaching, use our Python tutorials. To test yourself, try quizzes or coding challenges. Clean up style with the Python formatter.