SoFunction
Updated on 2024-11-19

Python Class and Instance Methods (@classmethod), Static Methods (@staticmethod) Principles and Usage Analysis

This article is an example of Python class and instance methods (@classmethod), static methods (@staticmethod). It is shared for your reference as follows:

(class method, @classmethod):

class Tool(object):
  # Define class attributes using assignment statements to record the number of all instantiated tool objects
  count = 0
  # @classmethod Defines a class method. The first argument is cls (cls is used to access class attributes and class methods, not instance attributes/methods).
  @classmethod
  def show_tool_count(cls):
    # Cannot access instance properties
    print("Number of tool objects %d" % ) # cls.class attribute name Access to class attributes (in class methods)
  def __init__(self, name):
     = name # Instance properties
    # Class name. Class Attribute Name Access to class attributes (in instance methods)
     += 1
# Instantiate tool objects
tool1 = Tool("The Axe.")  # tool1.__class__ attribute points to the class object. tool1.__class__.count instance object accesses class attribute
tool2 = Tool("Hammer.")
# Class name. Class Methods Calling Class Methods
Tool.show_tool_count()

Run results:

Number of tool objects 2

(static method, @staticmethod):

class Dog(object):
  # @staticmethod Defines static methods; class attributes/methods and instance attributes/methods cannot be accessed inside static methods. No default parameters need to be passed.
  # Static methods in Python do the same thing as regular functions defined outside a class, except that they indicate that the function is for use by that class only.
  @staticmethod
  def run():
    # Cannot access instance attributes/class attributes
    print("The puppies are going to run...")
# Class name. Static method name Invoke static method without creating object (can also be invoked by instance object).
()

Run results:

The puppy is going to run...



Readers interested in more Python related content can check out this site's topic: thePython Object-Oriented Programming Introductory and Advanced Tutorials》、《Python Data Structures and Algorithms Tutorial》、《Summary of Python function usage tips》、《Summary of Python string manipulation techniques》、《Summary of Python coding manipulation techniquesand thePython introductory and advanced classic tutorials

I hope that what I have said in this article will help you in Python programming.