Python class methods, static methods, and properties
@classmethod, @staticmethod, @property, setter, deleter, cls vs self, factory pattern with classmethod
Special Method Types
Python has three method types. Instance methods receive self. Class methods receive the class (cls). Static methods receive neither — they are plain functions scoped to the class namespace.
class Circle:
PI = 3.14159
def __init__(self, radius):
self._radius = radius
@property
def radius(self):
return self._radius
@radius.setter
def radius(self, value):
if value < 0:
raise ValueError("Radius must be non-negative")
self._radius = value
@classmethod
def from_diameter(cls, diameter):
return cls(diameter / 2)
@staticmethod
def is_valid_radius(r):
return r > 0
c = Circle.from_diameter(10)
print(c.radius) # 5.0
c.radius = 7
print(Circle.is_valid_radius(-1)) # False
Properties
A @property turns a method into a computed attribute with controlled access. Add a @name.setter to allow assignment with validation. This is the Pythonic alternative to Java-style get/set methods.
Properties enforce encapsulation without the verbose getter/setter boilerplate common in Java. They let you add validation, caching, or computation to what looks like a plain attribute access from the outside. If you later need to add validation to a public attribute, you can convert it to a property without changing the calling code — this is why Python code starts with public attributes rather than defensive getters. Use a leading underscore (_attr) to signal an attribute is internal by convention, and a double underscore (__attr) to trigger name mangling.
