In-Depth Analysis of Class Methods, Instance Methods, and Static Methods in Python

Follow and star to learn new Python skills every day

Due to changes in the public account’s push rules, please click “View” and add “Star” to get exciting technical shares at the first time

Source from the internet, please delete if infringing

In the world of object-oriented programming in Python, class methods, instance methods, and static methods are like three unique keys, each unlocking different functionalities and logics. Understanding the differences and relationships between them is crucial for building efficient, readable, and maintainable code systems.

1. Instance Variables

Instance variables are unique attributes belonging to each instance object of a class. They are initialized during the instantiation process, and each instance has its own independent copy. This means that instance variables with the same name in different instances can store different values without interfering with each other.

For example, in the Dog class, name, color, and weight are typical instance variables:

class Dog:    # name, color... -> instance variables, each specific dog has its own    def __init__(self, name, color, weight):        self.name = name        self.color = color        self.weight = weight

When we create two instances d1 = Dog(‘Big Yellow’, ‘Yellow’, 10) and d2 = Dog(‘Wealthy’, ‘Black’, 8), d1’s name is Big Yellow, color is Yellow, and weight is 10; while d2’s name is Wealthy, color is Black, and weight is 8. These instance variables store unique information for each Dog instance, allowing each instance to be clearly identified and distinguished in the program, and to exhibit different behaviors or characteristics based on their instance variable values. For example, d1 may behave differently from d2 in terms of running speed and endurance due to its heavier weight.

2. Class Variables

Class variables are variables associated with the entire class, shared by all instances of the class. Regardless of how many instances of the class are created, there is only one copy of the class variable in memory, and modifications to the class variable will affect all instances of the class.

In the Dog class, dogbook is a class variable:

class Dog:    dogbook = {'Yellow': 30, 'Black': 20, 'White': 0}  # Class variable: only one in the class    # name, color... -> instance variables, each specific dog has its own    def __init__(self, name, color, weight):        self.name = name        self.color = color        self.weight = weight

This dogbook can be used to record the quantity of dogs of different colors. All Dog instances can access this class variable, and if the quantity of a certain color of dog is modified through an instance or the class itself, this modification will take effect across the entire class, and other instances will see the updated state of dogbook. Class variables are typically used to store information related to the class as a whole, such as global configuration information and shared data, which do not need to be stored separately in each instance, thus saving memory space and facilitating unified management and maintenance.

3. Instance Methods

Instance methods are the most common and fundamental type of method in object-oriented programming. Their hallmark feature is that the first parameter must be self, which is not a keyword but a conventional naming method representing the instance object itself. Through self, instance methods can delve into the internals of the instance object, freely accessing and flexibly manipulating the attributes unique to the instance object.

Using a simple Dog class as an example, we can clearly see the operation mechanism of instance methods:

class Dog:    dogbook = {'Yellow': 30, 'Black': 20, 'White': 0}  # Class variable: only one in the class    # name, color... -> instance variables, each specific dog has its own    def __init__(self, name, color, weight):        self.name = name        self.color = color        self.weight = weight    # Instance method: pass self as the first parameter, nothing else, can only be called by instance    def bark(self):        print(f'{self.name} barked')d1 = Dog('Big Yellow', "Yellow", 10)d1.bark()

In the above code, the __init__ method is a special instance method that is automatically called when creating an instance of the class, taking on the important mission of initializing the instance object’s attributes. The bark method is a typical instance method; when we create a Dog instance, for example, d1 = Dog(‘Big Yellow’, ‘Yellow’, 10), and then call d1.bark(), the self parameter is silently bound to the current instance object d1 by the Python interpreter. Because of this, the bark method can accurately access d1’s name attribute and print this information.

The core value of instance methods lies in their ability to customize behaviors and operations based on the uniqueness of each instance object. Different Dog instances have their own independent attribute values, and instance methods can exhibit different behaviors based on these different attributes, making each instance seem to have its own personality and life.

4. Class Methods

Class methods in Python are defined using the @classmethod decorator, with the first parameter conventionally named cls, which represents the class itself, not a specific instance of the class.

Let’s return to the Dog class example:

class Dog:        # Class method: belongs to the Dog class, not to a specific dog    @classmethod    def dog_num(cls):        num = 0        for v in cls.dogbook.values():            num += v        return numd1 = Dog('Big Yellow', "Yellow", 10)d1.bark()print(f'There are {Dog.dog_num()} dogs')print(f'There are {d1.dog_num()} dogs')    # Can also be called using an instance, Python will automatically pass Dog to the code

In this example, the dog_num class method is designed to calculate the total number of dogs. It directly accesses the class variable dogbook, iterates through its values, and accumulates them to derive the total count of all dogs. One major advantage of class methods is that they can be called directly without creating an instance of the class, using the call method Dog.dog_num. Of course, Python also allows class methods to be called using instances, such as d1.dog_num; in this case, the Python interpreter automatically passes the class object Dog implicitly into the method, allowing operations to still proceed smoothly at the class level.

The main application scenarios for class methods typically focus on operations related to the class as a whole. For example, modifications, queries, or statistics related to class variables, which often do not depend on a specific instance object but are closely tied to the concept and state of the entire class. Additionally, class methods often play an important role in creating factory methods, which can return instances of the class based on specific rules or input parameters, providing a more flexible and controllable way to create objects.

5. Static Methods

Static methods are a special type of method defined using the @staticmethod decorator. Unlike instance methods and class methods, static methods do not require the mandatory passing of self or cls parameters representing the instance or class object. Essentially, static methods are more like regular functions, except they are defined within the class’s namespace, thus logically associating them with the class.

For example, in the Dog class, the total_weight method:

class Dog:    @staticmethod    def total_weight(dogs):        total = 0        for dog in dogs:            total += dog.weight        return totalprint(f'The total weight of the dogs is {Dog.total_weight([d1, d2])} kg')

The total_weight static method calculates the total weight of a group of dogs. It takes a list of dog instances as a parameter, then iterates through this list, accumulating each instance’s weight attribute value, ultimately returning the total weight of all dogs. It is important to note that static methods cannot access instance attributes or class variables; their independence makes them primarily suitable for operations that are logically related to the class but do not depend on the specific state of the class or instance. Such operations often have a utility characteristic, such as data transformation, validation, or some simple calculation logic, which, while related to the class, do not require delving into the internal state of the class or instance to obtain information.

6. Summary

Instance variables store unique data for each instance object, allowing instances to be independent and possess personalized characteristics.

Class variables provide shared data resources for the entire class, facilitating unified management and maintenance of global information related to the class.

Instance methods focus on handling individual behaviors of instance objects, accessing instance variables through self to achieve personalized operations and expressions.

Class methods focus on the overall level of the class, using cls to operate on class variables, handling transactions related to the class as a whole, such as statistics and configuration.

Static methods, as independent utility functions within the class, are relatively separated from the state of the class and instances, executing some general operations that are logically related to the class but do not depend on internal states.

The complete code is as follows:

class Dog:    dogbook = {'Yellow': 30, 'Black': 20, 'White': 0}  # Class variable: only one in the class    # name, color... -> instance variables, each specific dog has its own    def __init__(self, name, color, weight):        self.name = name        self.color = color        self.weight = weight        # Omitted several lines, should update the quantity of dogbook    # Instance method: pass self as the first parameter, nothing else, can only be called by instance    def bark(self):        print(f'{self.name} barked')# d1 = Dog('Big Yellow', "Yellow", 10)# d1.bark()# Class method: belongs to the Dog class, not to a specific dog    @classmethod    def dog_num(cls):        num = 0        for v in cls.dogbook.values():            num += v        return num# d1 = Dog('Big Yellow', "Yellow", 10)# d1.bark()# print(f'There are {Dog.dog_num()} dogs')# print(f'There are {d1.dog_num()} dogs')    # Can also be called using an instance, Python will automatically pass Dog to the code# Static method: does not require passing self, cls, unrelated to the class    @staticmethod    def total_weight(dogs):        total = 0        for dog in dogs:            total += dog.weight        return totalprint(f'There are {Dog.dog_num()} dogs')d1 = Dog('Big Yellow', "Yellow", 10)d1.bark()print(f'There are {d1.dog_num()} dogs')d2 = Dog('Wealthy', 'Black', 8)d2.bark()print(f'The total weight of the dogs is {Dog.total_weight([d1, d2])} kg')

The running result is as follows:

In-Depth Analysis of Class Methods, Instance Methods, and Static Methods in Python

Conclusion

In practical Python programming, choosing to use instance methods, class methods, and static methods wisely and cleverly is like carefully selecting suitable building materials and structural design plans when constructing a large building. The right choice can make the code structure clearer, the logic of each module more rigorous and reasonable, thereby greatly improving the readability and maintainability of the code. For example, when we need to describe an object’s individual behavior, instance methods are undoubtedly the best choice; when it comes to statistics, management, or creating a unified entry point for class information, class methods can exert their unique advantages; and for those operations that are related to the class but relatively independent, static methods can provide concise and efficient solutions.

By deeply analyzing and mastering these three types of methods, we can build complex and powerful program systems in the field of Python’s object-oriented programming more adeptly, continuously improving the quality of our code and development efficiency, laying a solid foundation for creating excellent software products.


Click to follow the public account below to get free Python public courses and hundreds of GB of learning materials organized by experts, including but not limited to Python e-books, tutorials, project orders, source code, etc.


▲ Click to follow - Free to receive

Recommended Reading
Can Python now run Mojo?
Complete explanation of Python basic syntax! 26,000 words, 38 images!
Comparison of Python virtual environment tools: venv, conda, and uv, why I ultimately chose uv?
A calculator developed based on Python's tkinter library (complete code)


Click to read the original text


Leave a Comment