ClassMethod and staicMethod in Python Class
文章来源: Unix19982024-04-28 16:54:08

1. Class methods (using @classmethod decorator):

  • Purpose: Class methods operate on the class itself rather than specific instances. They are often used for:
    • Factory methods: Creating objects with different configurations based on provided arguments.
    • Utility functions: Performing actions related to the class as a whole, such as validation or data manipulation.
  • Calling: You call class methods using the class name followed by a dot and the method name (e.g., ClassName.class_method()).



class Person:
    def __init__(self, name, age): = name
        self.age = age

    def from_birth_year(cls, name, birth_year):
        age = 2024 - birth_year
        return cls(name, age)  # Returning a new instance

person1 = Person.from_birth_year("Alice", 1990)  # Call class method without creating Person first





2. Static methods (using @staticmethod decorator):

  • Purpose: Static methods are essentially regular functions defined within the class for reusability. They don't receive the class or instance automatically as arguments. They are useful for:
    • Helper functions: Providing utility functions that don't rely on class or instance attributes and can be used independently.
    • Mathematical or string manipulation functions: Implementing functions that don't necessarily relate to the class itself but can be conveniently grouped within the class.
  • Calling: You call static methods similar to class methods (e.g., ClassName.static_method()).


example :


class Utility:
    def is_even(number):
        return number % 2 == 0

is_eight_even = Utility.is_even(8)  # Call static method without creating Utility first