Python Class Methods, Static Methods and Properties: What Each One Receives
Instance methods get self, class methods get cls, static methods get nothing. Then properties, setters and deleters, with small runnable files and their real output.
What you will learn
- Explain what Python passes first to instance, class and static methods
- Write a class method as an alternate constructor with cls
- Choose between an instance, class or static method for a job
- Use @property with a setter to compute values and check what gets stored
Before you start
- Python classes, objects and self
A Python class can hold three kinds of method: instance methods, class methods and static methods. They look almost the same on the page. The only real difference is what Python hands in as the first argument.
Think about a library. To ask how many books one member has borrowed, you need that member's card. To change the borrowing limit for everyone, you need the library itself, not anyone's card. To work out a late fee on the desk calculator, you need neither. The calculator just lives at the desk because that's a handy place for it.
Those are the three kinds of method. After them we'll look at properties, where a method reads like a plain attribute. Every file below is small and runnable, and every output is from a real run.
The @ sign is just a wrapper
You'll see @classmethod, @staticmethod and @property above methods. These are decorators that come with Python. A decorator wraps a function, and you can do the wrapping by hand to prove there's no magic:
class Sample:
def hello(cls):
return f"I got {cls.__name__}"
hello = classmethod(hello)
print(Sample.hello())
I got Sample
The line hello = classmethod(hello) does exactly what writing @classmethod above the def does. When we call it on the class, the class gets passed in.
What rides in first: self, cls or nothing
Here is one class with one method of each kind:
class Sample:
def instance_way(self):
return type(self).__name__
@classmethod
def class_way(cls):
return cls.__name__
@staticmethod
def static_way():
return "nothing was passed in"
d = Sample()
print(d.instance_way())
print(Sample.class_way())
print(d.class_way())
print(Sample.static_way())
Sample
Sample
Sample
nothing was passed in
d.instance_way(): Python passes the object before the dot in asself.Sample.class_way(): with@classmethod, Python passes the class. We call itclsbecauseclassis already a keyword.d.class_way(): called on the object, it still gets the class, not the object. That's why the third line is the same.Sample.static_way(): with@staticmethod, Python passes nothing. Noself, nocls, so the brackets are empty.
Instance methods: the default
If you write nothing above a method, it's an instance method. That's what you'll use most of the time. Use one when the job needs one object's data.
class Dog:
def __init__(self, name, breed):
self.name = name
self.breed = breed
self.tricks = []
def bark(self):
return f"{self.name} says Woof!"
def learn_trick(self, trick):
self.tricks.append(trick)
def describe(self):
t = ", ".join(self.tricks) or "none yet"
return f"{self.name} ({self.breed}) knows: {t}"
rex = Dog("Rex", "Labrador")
print(rex.describe())
rex.learn_trick("sit")
print(rex.describe())
print(Dog.describe(rex))
Rex (Labrador) knows: none yet
Rex (Labrador) knows: sit
Rex (Labrador) knows: sit
When we call rex.learn_trick("sit"), self is Rex, so "sit" goes onto Rex's own list. The last line, Dog.describe(rex), is the long way of writing rex.describe(). It prints the same thing because self is still Rex.
Class methods: work on the class
Use a class method when the job is about the class, not about one object. Here raise_percentage sits on the class, at 1.05, which is a 5% raise for everybody.
class Employee:
raise_percentage = 1.05
def __init__(self, name, salary):
self.name = name
self.salary = salary
@classmethod
def set_raise(cls, percentage):
cls.raise_percentage = percentage
alice = Employee("Alice", 75000)
bob = Employee("Bob", 60000)
print(alice.raise_percentage, bob.raise_percentage)
Employee.set_raise(1.10)
print(alice.raise_percentage, bob.raise_percentage)
1.05 1.05
1.1 1.1
Neither Alice nor Bob has a raise_percentage of their own, so Python looks it up on the class. set_raise changes the value on the class, in one place, and both objects see the new value. We never touched Alice or Bob.
The most common use: an alternate constructor
Say your data arrives as text, like "Alice-75000", but __init__ wants a name and a number. A class method can build the object for you:
class Employee:
def __init__(self, name, salary):
self.name = name
self.salary = salary
@classmethod
def from_string(cls, emp_str):
name, salary = emp_str.split("-")
return cls(name, int(salary))
emp = Employee.from_string("Alice-75000")
print(emp.name, emp.salary)
print(type(emp.salary))
Alice 75000
<class 'int'>
split("-") cuts the text at the dash, giving a name and a salary, both still text. int() turns the salary into a number. Then cls(name, int(salary)) is the same as calling Employee(...), so __init__ runs and a new object comes back.
We write cls rather than Employee so the method keeps working if the class is renamed, or if another class is built on top of it.
Static methods: plain functions kept in the class
A static method gets no self and no cls. It's a plain function that lives inside the class to keep related things together.
class MathUtils:
@staticmethod
def is_even(n):
return n % 2 == 0
@staticmethod
def fahrenheit_to_celsius(f):
return (f - 32) * 5 / 9
@staticmethod
def clamp(value, low, high):
return max(low, min(value, high))
print(MathUtils.is_even(42))
print(MathUtils.fahrenheit_to_celsius(212))
print(MathUtils.clamp(150, 0, 100))
True
100.0
100
We never built an object; we just used the class name. You could call these on an object too, but they would still get nothing. A static method can't see the object or the class unless you pass them in.
Which one should you use?
Ask two questions, in order:
- Does it need this object's data? Then it's an instance method.
describereads the name and the tricks. - If not, does it need the class? Then it's a class method.
from_stringbuilds a new object withcls. - Neither? Then it's a static method.
is_evenonly needs the number you give it.
Most methods stop at the first question. The other two you'll use once in a while.
All three in one class
class Pizza:
total_pizzas = 0
def __init__(self, size, toppings):
self.size = size
self.toppings = toppings
Pizza.total_pizzas += 1
def describe(self):
n = len(self.toppings)
return f"{self.size} pizza, {n} toppings"
@classmethod
def margherita(cls, size="medium"):
top = ["mozzarella", "basil", "tomato"]
return cls(size, top)
@staticmethod
def validate_size(size):
return size in ("small", "medium", "large")
p = Pizza.margherita("large")
print(p.describe())
print(Pizza.validate_size("huge"))
print(Pizza.total_pizzas)
large pizza, 3 toppings
False
1
margherita is a class method that builds a pizza with the toppings already decided, so __init__ runs and the total goes from 0 to 1. describe is an instance method. validate_size is a static method; "huge" isn't one of the three sizes, so it returns False. Each method takes only what it needs.
Properties: a value that can't go stale
First, the problem properties solve. This class works out Fahrenheit once, in __init__, and stores it:
class Temperature:
def __init__(self, celsius):
self.celsius = celsius
self.fahrenheit = celsius * 9 / 5 + 32
t = Temperature(100)
print(t.fahrenheit)
t.celsius = 0
print(t.fahrenheit)
212.0
212.0
We changed Celsius to 0, but Fahrenheit still says 212.0. It was worked out one time and nothing updates it. It's like a note on the fridge saying how much milk is left: right when you wrote it, wrong later. We want a value that is worked out when you read it.
class Temperature:
def __init__(self, celsius):
self._celsius = celsius
@property
def celsius(self):
return self._celsius
@property
def fahrenheit(self):
return self._celsius * 9 / 5 + 32
temp = Temperature(100)
print(temp.fahrenheit)
print(temp.celsius)
212.0
100
We store the value as _celsius. The underscore is a naming habit that says "this one is for the class itself". fahrenheit is still a method, with a def and a return, but look at the call: temp.fahrenheit, with no brackets. It reads like an attribute and runs like a method, so it's worked out each time and can't go stale. A method like this that gives you a value is called a getter.
A property on its own is read-only
class Temperature:
def __init__(self, celsius):
self._celsius = celsius
@property
def fahrenheit(self):
return self._celsius * 9 / 5 + 32
temp = Temperature(100)
temp.fahrenheit = 50
Traceback (most recent call last):
File "S03L02_Methods\read_only.py", line 11, in <module>
temp.fahrenheit = 50
^^^^^^^^^^^^^^^
AttributeError: property 'fahrenheit' of 'Temperature' object has no setter
Read the last line: the property has no setter. That's often what you want. A value that's worked out shouldn't be written over.
Setters and deleters
To allow writing, add a setter. @property gives the getter, and @name.setter adds a second method with the same name, for writing. @name.deleter adds a third, for del.
class Person:
def __init__(self, name):
self.name = name
@property
def name(self):
return self._name
@name.setter
def name(self, value):
if not isinstance(value, str):
raise TypeError("Name must be a string")
if len(value.strip()) == 0:
raise ValueError("Name cannot be empty")
self._name = value.strip().title()
@name.deleter
def name(self):
print("Deleting name...")
del self._name
p = Person(" alice ")
print(p.name)
p.name = "bob smith"
print(p.name)
del p.name
Alice
Bob Smith
Deleting name...
Here's the part people miss. Inside __init__, self.name = name doesn't just store the value. Because name is a property, that line goes through the setter. So " alice " passes the checks, and strip() and title() clean it up to "Alice".
The value is stored as _name. It needs a different name, because writing to self.name inside the setter would call the setter again, and again.
p.name = "bob smith" looks like a plain assignment, but it runs the setter too. The caller just assigns, and the class stays in charge of what gets stored.
What the checks catch
The same Person class (getter and setter), tried with two bad names:
class Person:
def __init__(self, name):
self.name = name
@property
def name(self):
return self._name
@name.setter
def name(self, value):
if not isinstance(value, str):
raise TypeError("Name must be a string")
if len(value.strip()) == 0:
raise ValueError("Name cannot be empty")
self._name = value.strip().title()
for bad in (42, " "):
try:
Person(bad)
except (TypeError, ValueError) as err:
print(type(err).__name__, "-", err)
TypeError - Name must be a string
ValueError - Name cannot be empty
42 isn't a string, so isinstance fails and we get a TypeError. A name of only spaces is a string, but after strip() its length is zero, so we get a ValueError. Both went in through __init__, so you can't even build a person with a bad name.
Common mistakes
- Storing the value under the property's own name. Writing
self.name = ...inside thenamesetter calls the setter again. Store it asself._name. - Calling a property with brackets.
temp.fahrenheit()tries to call the float that the property returned. Read it astemp.fahrenheit. - Hard-coding the class name in a factory.
return Employee(...)works, butreturn cls(...)keeps working when the class is renamed or extended. - Reaching for static or class methods by default. If the method needs the object's data, it's an instance method. That's most methods.
Quick recap
| Kind | Decorator | First argument | Use it when |
|---|---|---|---|
| Instance method | none | self, the object | the job needs one object's data |
| Class method | @classmethod | cls, the class | the job is about the class, or builds an object (from_string) |
| Static method | @staticmethod | nothing | a helper that needs neither |
| Property | @property | self | a value worked out when it's read |
| Setter / deleter | @name.setter, @name.deleter | self (+ value) | you want to check or clean what gets written |
You won't write setters and deleters every day. You'll mostly meet them inside packages, so it pays to recognise them when you read them.
Try it yourself
Add a fahrenheit setter to Temperature that converts the value back to Celsius and stores it in _celsius. Or prompt an AI tool to write it, then read every line it gives you.
Built this? Share your solution in the StudyEasy AI Community.
Join free on Skool →StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (opens in a new tab)Full Stack Python & React: Django, FastAPI, Flask + AI
Python, Django, FastAPI, Flask, React, Docker, AWS, local LLMs and AI vibe coding.View on Udemy ↗: Full Stack Python & React: Django, FastAPI, Flask + AI (opens in a new tab)