Python: method, classmethod, and staticmethod

99 阅读1分钟

python_class_method_vs_static_method_vs_instance_method.webp Both classmethod and staticmethod decorators in Python are used to define methods that are bound to the class rather than the instance. However, they serve different purposes and have some key differences:

  1. classmethod:

    • A method decorated with @classmethod takes the class itself as its first parameter (usually named cls).
    • It has access to the class and its attributes but not to the instance-specific data.
    • It can be used to create class-level methods that operate on class-level data.
    
    class MyClass:
        class_variable = "Class Variable"
    
        @classmethod
        def class_method(cls):
            print(f"Class method accessing class_variable: {cls.class_variable}")
    
    MyClass.class_method()
    
  2. staticmethod:

    • A method decorated with @staticmethod does not take a reference to the class or instance as its first parameter.
    • It is a regular function that happens to be defined inside a class.
    • It does not have access to the class or instance, and it is often used for utility functions that don't depend on class or instance data.
    class MyClass:
        @staticmethod
        def static_method():
            print("Static method")
    
    MyClass.static_method()
    

In summary:

  • Use classmethod when you need access to the class itself and its attributes.
  • Use staticmethod when the method doesn't depend on the class or instance and behaves like a regular function.
  • 所有的method,在访问global variable时,是没有问题的。
a = 5

class CopyR:
    @staticmethod
    def cfile():
        global a  # This line is not strictly necessary if you're just reading the global variable
        print(a)  # Accessing the global variable 'a'

# Call the static method directly
CopyR.cfile()  # Output: 5

上面这个,木有问题。

class MyClass:
    class_variable = "Class Variable"

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

    @classmethod
    def class_method(cls):
        # Cannot access instance_variable directly in a class method
        # cls.instance_variable will raise an AttributeError
        print(f"Class method accessing class_variable: {cls.class_variable}")

    def instance_method(self):
        # Can access both class_variable and instance_variable in an instance method
        print(f"Instance method accessing class_variable: {self.class_variable}")
        print(f"Instance method accessing instance_variable: {self.instance_variable}")

# Create an instance of MyClass
obj = MyClass(instance_variable="Instance Variable")

# Call the class method
MyClass.class_method()

# Call the instance method
obj.instance_method()

When deciding between classmethod and staticmethod, consider whether the method needs access to the class (classmethod) or not (staticmethod). If the method requires access to the class but not to the instance, use classmethod. If it doesn't need access to either, use staticmethod. If it needs access to the instance, use a regular instance method without any special decorator.