Skip to content
Python

Python Instance, Class and Static Methods and @property

Ihsan Ullah · 15 min read
Python Class and Static Methods, Lesson 39 of the Python course: self, cls, @staticmethod and @property

Python course · Module 8: OOP in Python · Lesson 39 of 63

Quick answer: A Python class can have three kinds of methods. An instance method (the normal kind) gets the object as self. A class method, marked with @classmethod, gets the class itself as cls and is often used as a second way to create objects, such as ShoppingCart.from_json(text). A static method, marked with @staticmethod, gets nothing extra and is a plain helper function kept inside the class. @property turns a method into something you read like an attribute, such as cart.total, and with a setter it can check new values before they are stored.

In this lesson you will learn:

  • the difference between instance, class and static methods, and what each one receives
  • how to write a class method that creates objects in another way (an “alternative constructor”)
  • when a static method makes sense
  • how @property gives you computed attributes such as cart.total
  • how a property setter checks values, with a discount example

Before you start: finish Lesson 38, Python Classes and Objects: A Beginner’s Guide. We keep building the ShoppingCart class from that lesson. All examples were run on Linux with Python 3.14.6 and gave exactly the same output on Python 3.15.2, the newest release on python.org.

Instance, class and static methods side by side

Every method in Lesson 38 was an instance method: its first parameter is self, the object you call it on. Two decorators (the @ lines above a def) change what the first parameter is:

class ShoppingCart:
    currency = "USD"

    def __init__(self, owner):
        self.owner = owner
        self.items = {}

    def __repr__(self):
        return f"ShoppingCart({self.owner!r})"

    def instance_method(self):
        print("instance method got:", self)

    @classmethod
    def class_method(cls):
        print("class method got:", cls)

    @staticmethod
    def static_method():
        print("static method got: nothing")


cart = ShoppingCart("Amna")
cart.instance_method()
cart.class_method()
cart.static_method()

print("--- called on the class ---")
ShoppingCart.class_method()
ShoppingCart.static_method()
instance method got: ShoppingCart('Amna')
class method got: <class '__main__.ShoppingCart'>
static method got: nothing
--- called on the class ---
class method got: <class '__main__.ShoppingCart'>
static method got: nothing
Python classmethod vs staticmethod diagram from Lesson 39: an instance method receives the object as self, a class method receives the ShoppingCart class as cls, and a static method receives nothing extra.
What each kind of method receives: the object (self), the class (cls) or nothing.
  • The instance method got the object, ShoppingCart('Amna') (this text comes from __repr__).
  • The class method got the class, <class '__main__.ShoppingCart'>, even when we called it on the object. The built-in functions docs say: “A class method receives the class as an implicit first argument, just like an instance method receives the instance.”
  • The static method got nothing. The docs say: “A static method does not receive an implicit first argument.”
  • Class and static methods work on the class and on an object. Instance methods need an object.

cls is only a name, like self, but it is the usual one.

Class methods: another way to create objects

The most common use of a class method is an alternative constructor: a method that builds an object from some other kind of data. ShoppingCart("Bilal") makes an empty cart. But what if the cart was saved as JSON text, like in Lesson 34? A class method can read the text and return a full cart:

import json


class ShoppingCart:
    def __init__(self, owner):
        self.owner = owner
        self.items = {}

    def add_item(self, name, price, quantity=1):
        self.items[name] = (price, quantity)

    @classmethod
    def from_json(cls, text):
        """Make a cart from saved JSON text (an "alternative constructor")."""
        data = json.loads(text)
        cart = cls(data["owner"])
        for item in data["items"]:
            cart.add_item(item["name"], item["price"], item["quantity"])
        return cart

    def __repr__(self):
        return f"ShoppingCart({self.owner!r})"


saved = """{"owner": "Bilal",
            "items": [{"name": "pen", "price": 1.5, "quantity": 4},
                      {"name": "notebook", "price": 3.0, "quantity": 1}]}"""

cart = ShoppingCart.from_json(saved)
print(repr(cart))
print(cart.items)
ShoppingCart('Bilal')
{'pen': (1.5, 4), 'notebook': (3.0, 1)}
  • ShoppingCart.from_json(saved) is called on the class, because we have no cart yet.
  • cls(data["owner"]) is the same as ShoppingCart("Bilal"). The method then fills the new cart and returns it.
  • Why cls(...) and not ShoppingCart(...)? The docs say: “If a class method is called for a derived class, the derived class object is passed as the implied first argument.” So if you later make a special kind of cart based on ShoppingCart (that is inheritance, Lesson 40), from_json makes that special kind automatically.

Python itself has class methods like this. You may know dict.fromkeys() from Lesson 18:

stock = dict.fromkeys(["pen", "notebook", "bag"], 0)
print(stock)

print(float.from_number(7))
{'pen': 0, 'notebook': 0, 'bag': 0}
7.0

Both are called on the class. float.from_number() is new: the What’s New in Python 3.14 page says “Add class methods float.from_number() and complex.from_number()“, so this line needs Python 3.14 or newer.

Class methods that change class attributes

A class method can also change a class attribute, the shared kind from Lesson 38. This is where class methods behave differently from a normal assignment:

class ShoppingCart:
    currency = "USD"

    def __init__(self, owner):
        self.owner = owner
        self.items = {}

    @classmethod
    def set_currency(cls, code):
        cls.currency = code.upper()


amna = ShoppingCart("Amna")
bilal = ShoppingCart("Bilal")

ShoppingCart.set_currency("eur")
print(amna.currency, bilal.currency)

amna.set_currency("pkr")
print(amna.currency, bilal.currency, ShoppingCart.currency)
print(vars(amna))
EUR EUR
PKR PKR PKR
{'owner': 'Amna', 'items': {}}
  • ShoppingCart.set_currency("eur") changed the class attribute, so both carts now show EUR.
  • amna.set_currency("pkr") was called on Amna’s cart, but it changed the currency for every cart. The docs explain why: “The instance is ignored except for its class.” So cls was still ShoppingCart.
  • vars(amna) has no currency key. Compare Lesson 38, where bilal.currency = "PKR" created an instance attribute on Bilal’s cart only.

Static methods: helpers that live in the class

Some functions belong to a class’s topic but need neither the object nor the class, such as turning a price label like "$1,250.50" into a number. A static method keeps it inside ShoppingCart:

class ShoppingCart:
    def __init__(self, owner):
        self.owner = owner
        self.items = {}

    @staticmethod
    def parse_price(label):
        """Turn a price label like '$1,250.50' into a float."""
        return float(label.replace("$", "").replace(",", "").strip())

    def add_item(self, name, price_label, quantity=1):
        price = self.parse_price(price_label)
        self.items[name] = (price, quantity)


print(ShoppingCart.parse_price("$1,250.50"))

cart = ShoppingCart("Amna")
cart.add_item("headphones", "$49.99")
cart.add_item("pen", " $1.50 ", 4)
print(cart.items)
1250.5
{'headphones': (49.99, 1), 'pen': (1.5, 4)}
  • parse_price has no self and no cls. It uses only its argument, with replace() and strip() from Lesson 20 and float() from Lesson 8.
  • You can call it on the class, ShoppingCart.parse_price(...), or through an object, self.parse_price(...), as add_item() does.

A static method is no more powerful than a normal function. It only keeps related code together; a helper used by many classes is better as a normal function.

@property: methods you read like attributes

In Lesson 38 we called cart.total(). A total is really a value of the cart, so it is nicer to read it as cart.total, without brackets. @property does that:

class ShoppingCart:
    def __init__(self, owner):
        self.owner = owner
        self.items = {}

    def add_item(self, name, price, quantity=1):
        self.items[name] = (price, quantity)

    @property
    def total(self):
        return sum(price * quantity for price, quantity in self.items.values())


cart = ShoppingCart("Amna")
cart.add_item("pen", 1.5, 4)
print(cart.total)
cart.add_item("notebook", 3.0)
print(cart.total)

try:
    cart.total = 100
except AttributeError as err:
    print("AttributeError:", err)
6.0
9.0
AttributeError: property 'total' of 'ShoppingCart' object has no setter
  • cart.total runs the method on every read, so it is always up to date: 6.0, then 9.0.
  • You cannot assign to it. The docs say @property turns the method into a “getter” for a “read-only attribute with the same name”. Python 3.14.6 and 3.15.2 both say property 'total' of 'ShoppingCart' object has no setter.

Use a property for values that are quick to calculate, such as a total or a count. Slow work (reading a file, calling a website) is clearer as a normal method with brackets.

A property with a setter: check values before storing them

A property can also have a setter, a method that runs when you assign a value. We give the cart a discount in percent and only allow 0 to 50:

class ShoppingCart:
    def __init__(self, owner, discount=0):
        self.owner = owner
        self.items = {}
        self.discount = discount  # this line already uses the setter below

    def add_item(self, name, price, quantity=1):
        self.items[name] = (price, quantity)

    @property
    def discount(self):
        return self._discount

    @discount.setter
    def discount(self, percent):
        if not 0 <= percent <= 50:
            raise ValueError(f"discount must be 0 to 50 percent, got {percent}")
        self._discount = percent

    @property
    def total(self):
        subtotal = sum(price * quantity for price, quantity in self.items.values())
        return round(subtotal * (100 - self.discount) / 100, 2)


cart = ShoppingCart("Amna")
cart.add_item("pen", 1.5, 4)
cart.add_item("notebook", 3.0)
print(cart.discount, cart.total)

cart.discount = 10
print(cart.discount, cart.total)

try:
    cart.discount = 80
except ValueError as err:
    print("ValueError:", err)
print(cart.discount)

try:
    ShoppingCart("Bilal", discount=75)
except ValueError as err:
    print("ValueError:", err)

print(vars(cart))
0 9.0
10 8.1
ValueError: discount must be 0 to 50 percent, got 80
10
ValueError: discount must be 0 to 50 percent, got 75
{'owner': 'Amna', 'items': {'pen': (1.5, 4), 'notebook': (3.0, 1)}, '_discount': 10}
  • @discount.setter adds a setter to the discount property. The docs warn: “Be sure to give the additional functions the same name as the original property”. Both methods are called discount.
  • cart.discount = 10 called the setter, which stored the value in self._discount. The total dropped from 9.0 to 8.1.
  • cart.discount = 80 raised ValueError (the raise from Lesson 36), and the old value 10 was kept.
  • self.discount = discount in __init__ also went through the setter, so ShoppingCart("Bilal", discount=75) failed too. A bad cart is never created.
  • vars(cart) shows the stored name, _discount.

The underscore is a convention. The Python tutorial says “‘Private’ instance variables that cannot be accessed except from inside an object don’t exist in Python”, but “a name prefixed with an underscore (e.g. _spam) should be treated as a non-public part of the API”. Other code could still change cart._discount; the underscore only asks people not to.

A complete example: the cart with all four tools

Here is everything together. parse_price now also accepts plain numbers: isinstance() (from Lesson 26) checks for text first.

import json


class ShoppingCart:
    """A shopping cart: item name -> (price, quantity)."""

    currency = "USD"

    def __init__(self, owner, discount=0):
        self.owner = owner
        self.items = {}
        self.discount = discount

    # --- class method: an alternative constructor ---
    @classmethod
    def from_json(cls, text):
        data = json.loads(text)
        cart = cls(data["owner"], data.get("discount", 0))
        for item in data["items"]:
            cart.add_item(item["name"], item["price"], item["quantity"])
        return cart

    # --- helper that needs no cart and no class ---
    @staticmethod
    def parse_price(label):
        if isinstance(label, str):
            return float(label.replace("$", "").replace(",", "").strip())
        return float(label)

    # --- normal instance methods ---
    def add_item(self, name, price, quantity=1):
        if quantity < 1:
            raise ValueError(f"quantity must be at least 1, got {quantity}")
        self.items[name] = (self.parse_price(price), quantity)

    # --- properties: used like attributes ---
    @property
    def discount(self):
        return self._discount

    @discount.setter
    def discount(self, percent):
        if not 0 <= percent <= 50:
            raise ValueError(f"discount must be 0 to 50 percent, got {percent}")
        self._discount = percent

    @property
    def subtotal(self):
        return sum(price * quantity for price, quantity in self.items.values())

    @property
    def total(self):
        return round(self.subtotal * (100 - self.discount) / 100, 2)

    def __str__(self):
        return (f"{self.owner}: {len(self.items)} items, subtotal {self.subtotal:.2f}, "
                f"discount {self.discount}%, total {self.total:.2f} {self.currency}")


amna = ShoppingCart("Amna")
amna.add_item("pen", 1.5, 4)
amna.add_item("headphones", "$49.99")
print(amna)

saved = """{"owner": "Bilal", "discount": 5,
            "items": [{"name": "laptop", "price": "$1,200", "quantity": 1},
                      {"name": "mouse", "price": 25, "quantity": 2}]}"""
bilal = ShoppingCart.from_json(saved)
print(bilal)

bilal.discount = 20
print(bilal.total)
Amna: 2 items, subtotal 55.99, discount 0%, total 55.99 USD
Bilal: 2 items, subtotal 1250.00, discount 5%, total 1187.50 USD
1000.0
  • Amna’s cart: 4 × 1.50 + 49.99 = 55.99, with no discount.
  • Bilal’s cart came from JSON with a 5% discount: 1,200 + 2 × 25 = 1,250.00, and 95% of that is 1,187.50.
  • Changing bilal.discount to 20 changed bilal.total at once to 1000.0, because a property is calculated when you read it.

A simple rule: needs the object’s data? Instance method. Needs the class? Class method. Needs neither? Static method. A value to read or set like an attribute? Property.

Try it yourself

Exercise 1: Celsius and Fahrenheit

Write a Temperature class that stores celsius. Add a read-only property fahrenheit (celsius * 9 / 5 + 32). Print it for 25 °C, then set celsius to 0 and print it again. What happens if you assign to fahrenheit?

Exercise 2: Products from text lines

Write a Product class with name and price. Add a class method from_line(line) that reads text like "Pen,1.50", and a static method clean_name(text) that removes outer spaces and makes the name lowercase. Build products from three lines with a list comprehension.

Exercise 3: A safe price

Give Product a price property with a setter that raises ValueError for negative prices. Try to set -1 and -0.5, and show that the old price is kept.

Solutions

Solution 1

class Temperature:
    def __init__(self, celsius):
        self.celsius = celsius

    @property
    def fahrenheit(self):
        return self.celsius * 9 / 5 + 32


today = Temperature(25)
print(today.fahrenheit)
today.celsius = 0
print(today.fahrenheit)

try:
    today.fahrenheit = 100
except AttributeError as err:
    print("AttributeError:", err)
77.0
32.0
AttributeError: property 'fahrenheit' of 'Temperature' object has no setter

The property recalculates fahrenheit from celsius each time, and it has no setter, so assigning to it fails.

Solution 2

class Product:
    def __init__(self, name, price):
        self.name = self.clean_name(name)
        self.price = price

    @classmethod
    def from_line(cls, line):
        name, price = line.split(",")
        return cls(name, float(price))

    @staticmethod
    def clean_name(text):
        return text.strip().lower()

    def __repr__(self):
        return f"Product({self.name!r}, {self.price})"


lines = ["  Pen ,1.50", "NOTEBOOK,3", "Bag,20.0"]
products = [Product.from_line(line) for line in lines]
print(products)
print(Product.clean_name("  Water Bottle "))
[Product('pen', 1.5), Product('notebook', 3.0), Product('bag', 20.0)]
water bottle

from_line uses cls(...) to build each product, and clean_name works without any object. The list comprehension is from Lesson 21.

Solution 3

class Product:
    def __init__(self, name, price):
        self.name = name
        self.price = price  # goes through the setter

    @property
    def price(self):
        return self._price

    @price.setter
    def price(self, value):
        if value < 0:
            raise ValueError(f"price cannot be negative, got {value}")
        self._price = value


pen = Product("pen", 1.5)
pen.price = 2.0
print(pen.name, pen.price)

for bad in (-1, -0.5):
    try:
        pen.price = bad
    except ValueError as err:
        print("ValueError:", err)
print(pen.price)
pen 2.0
ValueError: price cannot be negative, got -1
ValueError: price cannot be negative, got -0.5
2.0

The setter stores only valid values in self._price, so the price stays 2.0 after both bad attempts.

Common mistakes

  • Forgetting @classmethod. Without it, from_json(cls, text) is a normal instance method, and ShoppingCart.from_json(text) puts the text into cls: TypeError: ShoppingCart.from_json() missing 1 required positional argument: 'text'.
  • Calling a property with brackets. cart.total() first reads the property (a number) and then tries to call it: TypeError: 'float' object is not callable. Write cart.total.
  • Giving the setter a different name. @discount.setter above def set_discount(...) does not add a setter to discount, so cart.discount = 10 fails with AttributeError: property 'discount' of 'ShoppingCart' object has no setter.
  • Assigning to the property inside its own setter. self.discount = percent inside the discount setter calls the setter again and again until RecursionError: maximum recursion depth exceeded. Store the value in self._discount.
  • Using self in a static method. A static method has no self, so len(self.items) gives NameError: name 'self' is not defined. If you need the object, make it an instance method.

Frequently asked questions

When should I use a classmethod vs a staticmethod in Python?

Use a class method when the method needs the class, most often to create and return a new object (from_json, from_line) or to change a class attribute. Use a static method when the method needs neither the object nor the class and is only a helper that belongs to the class’s topic.

What does @property do in Python?

@property turns a method into an attribute you read without brackets. Python runs the method each time you read the value, so it can be calculated from other attributes. Add a setter with @name.setter to control what happens when someone assigns a new value.

Do I need getters and setters in Python?

Usually not. Start with plain attributes like self.owner. If you later need to check or calculate the value, turn it into a property. Code that uses cart.discount does not change, because a property looks exactly like an attribute.

Summary

  • Instance methods get the object (self), class methods get the class (cls) and static methods get nothing extra.
  • @classmethod is the usual way to write alternative constructors like ShoppingCart.from_json(text); it returns cls(...).
  • A class method called on an object still changes the class, because “the instance is ignored except for its class”.
  • @staticmethod keeps a helper function inside the class; it cannot use self.
  • @property makes computed attributes such as cart.total, and @name.setter checks values before they are stored in an underscore attribute like self._discount.

Next lesson

Next: Lesson 40, Python Inheritance and super(): Reuse and Extend Classes.

Sources

Ihsan Ullah

Written & tested by Ihsan Ullah

Data analyst with 3 years of experience and a Bachelor's degree in Computer Science. I write clear, practical guides on data, SQL, Python and AI.

More about me →

Leave a comment

Your email address will not be published. Required fields are marked *