วันอาทิตย์ที่ 18 กุมภาพันธ์ พ.ศ. 2567

What is the purpose of the @staticmethod decorator in Python, and how does it differ from the @classmethod decorator? Provide an example to illustrate their usage.

 Q31: What is the purpose of the @staticmethod decorator in Python, and how does it differ from the @classmethod decorator? Provide an example to illustrate their usage.

A31:

  • Purpose of @staticmethod and @classmethod:

    • The @staticmethod decorator in Python is used to define a static method within a class. Static methods are associated with the class rather than instances and do not have access to instance-specific data.

    • The @classmethod decorator is used to define a class method within a class. Class methods take the class itself as the first parameter, allowing them to work with class-level data.

  • Difference and Example:

    • @staticmethod does not take the instance or class as its first parameter, making it independent of instance or class-specific data.

    • @classmethod takes the class as its first parameter, allowing access to class-specific data.

    class MathOperations: @staticmethod def add(x, y): return x + y @classmethod def multiply(cls, x, y): return x * y # Using static method result_add = MathOperations.add(3, 5) # Using class method result_multiply = MathOperations.multiply(3, 5)

    In this example, add is a static method, and multiply is a class method. The add method does not have access to the instance or class, while the multiply method can access class-specific data through the cls parameter.

ไม่มีความคิดเห็น:

แสดงความคิดเห็น

How does the Python Global Interpreter Lock (GIL) impact the performance of multi-threaded programs, and what strategies can be employed to mitigate its effects?

  Q10: How does the Python Global Interpreter Lock (GIL) impact the performance of multi-threaded programs, and what strategies can be emplo...