Keyboard Shortcuts N Next post
P Previous post
S Save / unsave
R Read aloud
T Toggle theme
/ Focus search
Esc Close panels
🔥
Ready to read...
Module 5 - Object-Oriented Programming Python Python OOP Python Programming: From Zero to Real-World Applications

Instance, Class, and Static Methods in Python

Reviewed & accurate
AI Summary

What You Will Learn

Intermediate

  • Instance methods (self)
  • Class methods (@classmethod, cls)
  • Static methods (@staticmethod)
Terminalpython
class MyClass:
    count = 0
    
    def __init__(self):
        MyClass.count += 1
    
    # Instance method - needs self, accesses instance data
    def instance_method(self):
        return f"Instance method. self={self}"
    
    # Class method - needs cls, accesses class data
    @classmethod
    def class_method(cls):
        return f"Class method. count={cls.count}"
    
    # Static method - no self, no cls. Just a function in a class.
    @staticmethod
    def static_method():
        return "Static method. No access to self or cls."

obj = MyClass()
print(obj.instance_method())   # Instance
print(MyClass.class_method())  # count=1
print(MyClass.static_method()) # Static
TypeDecoratorFirst paramAccess
Instance(none)selfInstance + class
Class@classmethodclsClass only
Static@staticmethod(none)Neither

Practical Exercise

Create a class with all 3 method types
Call each: obj.instance_method()
Call class method: MyClass.class_method()
Call static method: MyClass.static_method()

Key Takeaways

  • Instance method: takes self, accesses instance data.
  • Class method (@classmethod): takes cls, accesses class data.
  • Static method (@staticmethod): no self/cls, utility function.
  • Use class methods as alternative constructors.
  • Use static methods for utilities related to the class.
Previously: Lesson 31 covered attributes.
Today: You learned: Three types of methods in Python classes.
Next: Lesson 33 covers inheritance.
Test Your Knowledge
How did you find this?

Comments

Join the discussion! Sign in with your Google or Blogger account, or comment as Anonymous - no account needed. For quick questions, also reach me on Telegram @cytestch.

Comments