正文

Python decorator @classmethod and @staticmethod decorators

(2024-03-24 12:59:08) 下一個

In Python, both `@classmethod` and `@staticmethod` decorators can be used to define methods that are not bound to an instance of the class. This means they can be called on the class itself rather than on an instance of the class, and they do not require the `self` parameter.

However, there is a difference between them:

1. `@classmethod`: This decorator is used to define a method that operates on the class itself rather than on instances of the class. It receives a reference to the class (`cls`) as its first parameter, conventionally named `cls`. This allows you to access or modify class-level variables or to create new instances of the class.

2. `@staticmethod`: This decorator is used to define a method that does not access or modify class or instance state. It's essentially a regular function that belongs to the class namespace for organization purposes. Unlike `@classmethod`, it does not receive a reference to the class or instance. It behaves like a normal function defined within the class but has the advantage of being logically grouped with the class.

Here's an example demonstrating the usage of both:

```python
class MyClass:
    class_variable = 10

    def __init__(self, value):
        self.value = value

    @classmethod
    def class_method(cls):
        print("Class method")
        print("Class variable:", cls.class_variable)

    @staticmethod
    def static_method():
        print("Static method")

# Calling class methods
MyClass.class_method()  # Output: Class method n Class variable: 10
MyClass.static_method()  # Output: Static method
```

In summary:

- Both `@classmethod` and `@staticmethod` decorators allow you to define methods that can be called on the class itself without needing an instance.
- `@classmethod` receives a reference to the class (`cls`) as its first parameter, while `@staticmethod` does not receive any implicit reference to the class or instance.

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