SoFunction
Updated on 2024-11-19

Python instance methods, class methods, static methods difference in detail

1. Differences on parameters

Instance Methods: Instance methods are defined with at least one formal parameter ---> the instance object, usually self.

Class Methods: Class methods are defined with at least one formal parameter ---> the class object, usually cls.

Static Methods: Static methods can be defined without formal parameters.

2. On the difference between adding decorators when defining methods

Instance method: no need to add decorators

Class methods: need to add decorators ----> @classmethod

Static methods: need to add decorators ---> @staticmethod

3. Call:

1. Instance methods can be called directly through the object

2. But when you call it by class name, you need to create an object and pass the object in when you pass the parameter

3. Class methods can be called directly through the class name or through an object

4. Static methods can be called directly through the class name or through an object

4. Supplementary

1. Static methods cannot be inherited

2. Class methods cannot access instance variables, only class variables

class Dog():

  age = 3   # Class variables
  def __init__(self):
     = "XiaoBai"  # Instance variables

  def run(self):   # Instance methods
    print("{} years old's {} is running!".format(,))

  @classmethod
  def eat(cls):
    # print() # Class method, can't access instance variables (properties)
    print("XiaoHei is {} years old".format())  # Class methods can only access class variables

  @staticmethod
  def sleep(name):
    # Static methods have nothing to do with the class, they can only be a function of the class
    # Static methods can't access class and instance variables
    print("{} is sleeping".format(name))

d = Dog()
()   # Invoke instance methods by instantiating objects
(d) # Calling an instance method by class name requires passing the instance object in the method
()   # Invoke class methods by instantiating objects
()  # Invoke class methods by class name
("XiaoLan")  # Invoke static methods by instantiating objects
("XiaoLan") # Calling static methods by class name

This is the whole content of this article.