Skip to main content

Python OOP

Class & Static Methods

Complete lesson for Class & Static Methods using LEARNCODEGURU’s 6-level learning model — from basics to advanced practice, with Python data structures and OOP where relevant.

L1

Basics — Class & Static Methods

Section: Python OOP. Python class methods and static methods — @classmethod, @staticmethod, cls factories, and when to use each versus instance methods.

Three kinds of methods

  • Pick the narrowest tool that needs the data you have.
  • If you need instance attributes, use an instance method.
  • If you need the class (often to construct), use a classmethod.
KindDecoratorReceivesTypical use
Instance(none)self instanceRead/change object state
Class@classmethodcls classFactories, class-wide behaviour
Static@staticmethodneitherUtility related to the class theme

Instance methods (recap)

  • First argument is the instance (self).
  • Can read/write instance attributes and also see class attributes.
  • Called as obj.method() or Class.method(obj).
class Counter:
    def __init__(self, start=0):
        self.value = start

    def bump(self, n=1):
        self.value += n
        return self.value

c = Counter()
print(c.bump())
print(c.bump(2))

@classmethod basics

  • Declare with @classmethod. First parameter is conventionally cls.
  • cls is the class that was called — important for inheritance-friendly factories.
  • Called as Class.method(...) or obj.method(...) (still receives the class, not the instance, as cls).
class User:
    def __init__(self, name, role):
        self.name = name
        self.role = role

    @classmethod
    def guest(cls):
        return cls("Guest", "guest")

u = User.guest()
print(u.name, u.role)

Alternate constructors with classmethods

  • Named factories document intent better than cryptic __init__ flags.
  • Because factories receive cls, subclasses get the right type automatically.
  • Common names: from_string, from_json, from_row, now, empty.
class DateStamp:
    def __init__(self, year, month, day):
        self.year = year
        self.month = month
        self.day = day

    @classmethod
    def from_iso(cls, text):
        y, m, d = text.split("-")
        return cls(int(y), int(m), int(d))

    def __str__(self):
        return f"{self.year:04d}-{self.month:02d}-{self.day:02d}"

print(DateStamp.from_iso("2026-10-25"))

@staticmethod basics

  • Declare with @staticmethod. No automatic self or cls.
  • Behaves like a plain function stored on the class for namespacing.
  • Use when the logic relates to the class conceptually but needs neither instance nor class object.
class MathUtils:
    @staticmethod
    def clamp(value, low, high):
        return max(low, min(high, value))

print(MathUtils.clamp(15, 0, 10))
print(MathUtils.clamp(-2, 0, 10))

Class methods that touch class state

  • Classmethods are ideal for updating counters or shared configuration on the class.
  • Combine with class attributes for registries and object counts.
  • Instance methods can read those class attributes too when needed.
class Ticket:
    _next = 1
    sold = 0

    def __init__(self, event):
        self.event = event
        self.code = Ticket._next
        Ticket._next += 1
        Ticket.sold += 1

    @classmethod
    def sold_count(cls):
        return cls.sold

    @classmethod
    def reset_counter(cls):
        cls._next = 1
        cls.sold = 0

Ticket("Music")
Ticket("Music")
print(Ticket.sold_count())
Ticket.reset_counter()
print(Ticket.sold_count())

Instance vs class vs static — side by side

class Demo:
    kind = "demo"

    def __init__(self, name):
        self.name = name

    def instance_info(self):
        return f"instance={self.name}, kind={self.kind}"

    @classmethod
    def class_info(cls):
        return f"class={cls.__name__}, kind={cls.kind}"

    @staticmethod
    def static_info():
        return "no self, no cls"

d = Demo("alpha")
print(d.instance_info())
print(Demo.class_info())
print(Demo.static_info())

When to choose which

NeedChoose
Object fields (self.x)Instance method
Create instances / use subclass type@classmethod
Pure helper with class namespacing@staticmethod
Only module-level reuse, no class storyPlain module function
L2

Advanced — Class & Static Methods

Inheritance-friendly factories

  • Factories should return cls(...) not hard-coded Base(...).
  • Then Sub.from_text(...) builds a Sub automatically.
  • This is one of the strongest reasons to prefer classmethods over static factories.
class Animal:
    def __init__(self, name):
        self.name = name

    @classmethod
    def from_label(cls, label):
        return cls(label.title())

class Dog(Animal):
    def speak(self):
        return "woof"

d = Dog.from_label("rocky")
print(type(d).__name__, d.name, d.speak())

staticmethod vs module function

  • If a helper is generally useful, a module-level function may be clearer.
  • Keep a staticmethod when it is tightly tied to the class domain and you want it discoverable on the class.
  • Staticmethods do not participate specially in inheritance beyond normal attribute lookup.

Calling conventions and unbound surprises

  • Instance methods need an instance when called via the class.
  • Classmethods receive the class even when called via an instance.
  • Staticmethods ignore both and just take what you pass.
class Toy:
    def inst(self):
        return "inst"

    @classmethod
    def cls_m(cls):
        return cls.__name__

    @staticmethod
    def stat(x):
        return x * 2

t = Toy()
print(t.inst())
print(t.cls_m())
print(Toy.cls_m())
print(Toy.stat(5))

Class body and decorators order

  • Write @classmethod / @staticmethod directly above def.
  • With multiple decorators, order matters; keep these next to the function.
  • Do not forget the decorator — a bare method with cls as first name is still an instance method.
class Note:
    @classmethod
    def ping(cls):
        return "ok-" + cls.__name__

print(Note.ping())

Mix of factories and instance behaviour

  • A solid class often has a small __init__, a few classmethod constructors, and instance methods for behaviour.
  • Static helpers can preprocess arguments before construction.
  • Keep each method's dependency set obvious.
class Rgb:
    def __init__(self, r, g, b):
        self.r, self.g, self.b = r, g, b

    @staticmethod
    def _parse_hex(text):
        h = text.lstrip("#")
        return int(h[0:2], 16), int(h[2:4], 16), int(h[4:6], 16)

    @classmethod
    def from_hex(cls, text):
        return cls(*cls._parse_hex(text))

    def as_tuple(self):
        return self.r, self.g, self.b

print(Rgb.from_hex("#112233").as_tuple())
L3

Tricky Interview Points

Q1) What is a classmethod?

Answer A method declared with @classmethod that receives the class (cls) as its first argument instead of an instance.

Q2) What is a staticmethod?

Answer A method declared with @staticmethod that receives neither instance nor class automatically; it is a namespaced function.

Q3) Why use classmethods as constructors?

Answer They provide named alternate constructors and, via cls, correctly instantiate subclasses.

Q4) Difference between classmethod and staticmethod?

Answer Classmethods get cls and can create instances or access class state. Staticmethods get no special first arg.

Q5) Can you call a classmethod on an instance?

Answer Yes. obj.factory() still passes the instance's class as cls.

Q6) When is a plain function better than staticmethod?

Answer When the helper is general and not part of the class story — put it at module level.

Q7) What does cls mean?

Answer Convention for the class object passed into a classmethod (similar role to self for instances).

Q8) Do staticmethods see class attributes automatically?

Answer No. They must hard-code the class name or accept values as parameters.

Q9) Common factory naming patterns?

Answer from_str, from_json, from_dict, guest, empty, now — names that say how construction differs.

Q10) What happens if you forget @classmethod but still name the first arg cls?

Answer It remains an instance method; calling Class.fn() without an instance fails, and via instance the instance is passed as "cls".

Q11) How do classmethods help inheritance?

Answer Using cls(...) inside the factory builds whatever class was actually invoked, including subclasses.

Q12) Instance vs class attribute access from classmethod?

Answer Classmethods naturally access class attributes via cls. They do not have a specific instance unless you pass one in.

L4

Simple Programs

User factories

class User:
    def __init__(self, name, role):
        self.name = name
        self.role = role

    @classmethod
    def guest(cls):
        return cls("Guest", "guest")

    @classmethod
    def admin(cls, name):
        return cls(name, "admin")

    def __str__(self):
        return f"{self.name} ({self.role})"

print(User("Asha", "member"))
print(User.guest())
print(User.admin("Root"))

ISO date factory

class SimpleDate:
    def __init__(self, y, m, d):
        self.y, self.m, self.d = y, m, d

    @classmethod
    def from_iso(cls, text):
        y, m, d = map(int, text.split("-"))
        return cls(y, m, d)

    def __str__(self):
        return f"{self.y:04d}-{self.m:02d}-{self.d:02d}"

print(SimpleDate.from_iso("2026-10-25"))

Static validators + class factory

class Email:
    def __init__(self, address):
        self.address = address

    @staticmethod
    def is_valid(address):
        return "@" in address and "." in address.split("@")[-1]

    @classmethod
    def create(cls, address):
        if not cls.is_valid(address):
            raise ValueError("invalid email")
        return cls(address)

print(Email.is_valid("a@b.com"))
print(Email.create("asha@example.com").address)
try:
    Email.create("bad")
except ValueError as e:
    print(e)

Subclass keeps factory type

class Person:
    def __init__(self, name):
        self.name = name

    @classmethod
    def from_pair(cls, text):
        return cls(text.strip().title())

class Employee(Person):
    def role(self):
        return "staff"

e = Employee.from_pair("  ravi kumar ")
print(type(e).__name__, e.name, e.role())

Class counter with classmethods

class Session:
    active = 0

    def __init__(self, user):
        self.user = user
        Session.active += 1

    def close(self):
        Session.active -= 1

    @classmethod
    def active_count(cls):
        return cls.active

s1 = Session("A")
s2 = Session("B")
print(Session.active_count())
s1.close()
print(Session.active_count())

Rgb from hex using static + classmethod

class Rgb:
    def __init__(self, r, g, b):
        self.r, self.g, self.b = r, g, b

    @staticmethod
    def parse_hex(text):
        h = text.lstrip("#")
        return int(h[0:2], 16), int(h[2:4], 16), int(h[4:6], 16)

    @classmethod
    def from_hex(cls, text):
        return cls(*Rgb.parse_hex(text))

    def __str__(self):
        return f"rgb({self.r}, {self.g}, {self.b})"

print(Rgb.from_hex("#ff8800"))
L5

Problem Solving Tricks

  • Need self.x? Instance method. Need to construct with subclass awareness? Classmethod. Pure helper? Staticmethod or module function.
  • Always build with cls(...) inside classmethod factories.
  • Name factories clearly: from_iso, guest, empty.
  • Put @classmethod / @staticmethod immediately above def.
  • Calling obj.classmeth() still passes the class as cls.
  • Staticmethods cannot see instance state unless you pass it in.
  • Prefer module functions for generic utilities not tied to one type.
  • Combine static parsers with classmethod constructors for clean APIs.
  • Class attributes + classmethods make simple registries and counters.
  • Forgetting the decorator is a frequent interview trap — know the symptoms.
L6

Practice Programs List

  1. Write User.guest and User.admin classmethod factories.
  2. Add SimpleDate.from_iso and print formatted dates.
  3. Create Email.is_valid staticmethod and Email.create classmethod.
  4. Show that a subclass calling an inherited factory returns the subclass type.
  5. Track active sessions with a class attribute and active_count classmethod.
  6. Build Rgb.from_hex using a static parse helper.
  7. Compare the same helper as staticmethod vs module-level function in comments.
  8. Intentionally omit @classmethod and observe the error; then fix it.
  9. Write a class with all three method kinds and call each both ways (via class and instance) where valid.
  10. Refactor a boolean-flag __init__ into two named classmethod constructors.
  11. Implement from_dict and to_dict style helpers for a small data class.
  12. List four real-life factory names you would use in a ticket booking system.