正文

ClassMethod and staicMethod in Python Class

(2024-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()).

 

Example:

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

    @classmethod
    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:
    @staticmethod
    def is_even(number):
        return number % 2 == 0

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

 

[ 打印 ]
閱讀 ()評論 (0)
評論
目前還沒有任何評論
登錄後才可評論.