Python Learning Notes: Detailed Explanation of Class Methods and Static Methods

Hello everyone! Today I bring you the twenty-ninth learning note, which is still about basic knowledge. Let’s talk about two special methods in Python classes: class methods and static methods. These two methods are very practical in daily development and can help us better organize our code.

1. Static Methods: Utility Functions Independent of Class

1. Basic Concept

Static methods are defined using the<span><span>@staticmethod</span></span>decorator, which:

  • Does not require passing<span><span>self</span></span>or<span><span>cls</span></span>parameters

  • Is independent of both class and object

  • Essentially, it is a regular function defined within a class

class MathUtils:
    @staticmethod
    def add(a, b):
        """Addition utility method"""
        return a + b
    @staticmethod
    def is_even(number):
        """Determine if the number is even"""
        return number % 2 == 0
# Call method: ClassName.methodName()
result = MathUtils.add(5, 3) # Output: 8
print(MathUtils.is_even(4)) # Output: True
# Can also be called through an object
utils = MathUtils()
print(utils.is_even(5)) # Output: False

2. Applicable Scenarios

  • Utility functions (e.g., mathematical calculations, format conversions)

  • Helper methods that do not need to access class or object state

  • Functions related to the class but do not require instantiation

2. Class Methods: Operations at the Class Level

1. Basic Concept

Class methods are defined using the<span><span>@classmethod</span></span>decorator, which:

  • The first parameter must be<span><span>cls</span></span>(representing the class itself)

  • Can access and modify class attributes

  • Commonly used to create alternative constructors

class Circle:
    # Class attribute
    pi = 3.14159
    def __init__(self, radius):
        self.radius = radius
    @classmethod
    def from_diameter(cls, diameter):
        """Create a circle from diameter (alternative constructor)"""
        return cls(diameter / 2) # cls represents the class itself, equivalent to Circle()
    @classmethod
    def update_pi(cls, new_pi):
        """Modify the value of pi"""
        cls.pi = new_pi
        print(f"Pi has been updated to: {new_pi}")
# Use class method to create an object
circle1 = Circle.from_diameter(10) # Radius automatically calculated as 5
print(circle1.radius) # Output: 5.0
# Modify class attribute
Circle.update_pi(3.14) # Output: Pi has been updated to: 3.14

2. Practical Application Example

class Student:
    student_count = 0 # Class attribute to count total students
    def __init__(self, name):
        self.name = name
        Student.student_count += 1
    @classmethod
    def get_student_count(cls):
        """Get total number of students"""
        return cls.student_count
    @classmethod
    def create_from_string(cls, info_string):
        """Create a student object from a string"""
        name, age = info_string.split(',')
        student = cls(name) # Create new object
        student.age = int(age)
        return student
# Usage example
student1 = Student("Zhang San")
student2 = Student("Li Si")
print(Student.get_student_count()) # Output: 2
# Use class method to create an object
student3 = Student.create_from_string("Wang Wu,20")
print(student3.name, student3.age) # Output: Wang Wu 20

3. Comparison of the Three Methods

Method Type Decorator First Parameter Accessible Applicable Scenarios
Instance Method None self Instance attributes and methods Specific behavior of the object
Class Method @classmethod cls Class attributes and methods Class-level operations, alternative constructors
Static Method @staticmethod None None Utility functions, helper methods

4. Best Practice Recommendations

1. Selection Criteria:

  • If you need to access instance attributes → Instance Method

  • If you need to manipulate class attributes → Class Method

  • If neither is needed → Static Method

2. Naming Conventions:

  • Class methods are usually prefixed with<span><span>from_</span></span>to indicate alternative constructors

  • Static method names should reflect the characteristics of utility functions

3. Timing of Use:

class DateUtils:
    # Static method: pure utility function
    @staticmethod
    def is_valid_date(date_str):
        # Validate date format
        pass
    # Class method: requires class participation
    @classmethod
    def get_current_year(cls):
        # Get current year (may depend on class attributes)
        pass

5. Comprehensive Application Example

class BankAccount:
    # Class attributes
    interest_rate = 0.03 # Annual interest rate
    total_accounts = 0 # Total number of accounts
    def __init__(self, owner, balance=0):
        self.owner = owner
        self.balance = balance
        BankAccount.total_accounts += 1
    @classmethod
    def set_interest_rate(cls, new_rate):
        """Set interest rate (class method)"""
        cls.interest_rate = new_rate
        print(f"Interest rate has been adjusted to: {new_rate}")
    @staticmethod
    def calculate_interest(amount, years):
        """Calculate interest (static method)"""
        return amount * BankAccount.interest_rate * years
    @classmethod
    def get_total_accounts(cls):
        """Get total number of accounts"""
        return cls.total_accounts
# Usage example
account1 = BankAccount("Zhang San", 1000)
account2 = BankAccount("Li Si", 2000)
print(BankAccount.get_total_accounts()) # Output: 2
interest = BankAccount.calculate_interest(1000, 2)
# Calculate interest
print(f"Interest: {interest}") # Output: Interest: 60.0
BankAccount.set_interest_rate(0.035) # Adjust interest rate

Next time we will continue to explore Python, making progress a little bit every day. Let’s work hard together on the learning journey! If you have any questions, feel free to leave a comment for discussion~PS: A little note: Using method decorators correctly can make the code clearer and easier to maintain. It is important to choose the appropriate method type based on actual needs.

Leave a Comment