Python @staticmethod and normal method - unix1998/technical_notes GitHub Wiki
In Python, classes can have static methods, and class methods, and normal method ,normal method can be regarded as Dynamic method ? many programmes think python don't have explicit dynamic methods in class .
Here’s a detailed explanation of each:
Dynamic Methods (Instance Methods)
- Definition: These are methods that operate on an instance of the class (an object). They take the instance (
self
) as their first parameter. - Example:
class MyClass: def instance_method(self): print(f"Called instance_method of {self}") obj = MyClass() obj.instance_method() # Output: Called instance_method of <__main__.MyClass object at 0x...>
Static Methods
- Definition: Static methods do not take
self
orcls
as their first parameter. They behave like regular functions but belong to the class’s namespace. - Decorator:
@staticmethod
- Example:
class MyClass: @staticmethod def static_method(): print("Called static_method") MyClass.static_method() # Output: Called static_method obj = MyClass() obj.static_method() # Output: Called static_method
Class Methods
- Definition: Class methods take
cls
as their first parameter, representing the class itself. They can modify class state that applies across all instances of the class. - Decorator:
@classmethod
- Example:
class MyClass: class_variable = "class value" @classmethod def class_method(cls): print(f"Called class_method of {cls}") print(f"Class variable: {cls.class_variable}") MyClass.class_method() # Output: Called class_method of <class '__main__.MyClass'> # Output: Class variable: class value
Adding Methods Dynamically
You can add methods to a class or an instance dynamically at runtime. This demonstrates the flexibility of Python's object system:
Adding a Method to an Instance
class MyClass:
def __init__(self, value):
self.value = value
def dynamic_method(self):
print(f"Dynamic method called with value: {self.value}")
obj = MyClass(10)
obj.dynamic_method = dynamic_method.__get__(obj)
obj.dynamic_method() # Output: Dynamic method called with value: 10
Adding a Method to a Class
class MyClass:
def __init__(self, value):
self.value = value
def dynamic_class_method(self):
print(f"Dynamic class method called with value: {self.value}")
MyClass.dynamic_class_method = dynamic_class_method
obj = MyClass(20)
obj.dynamic_class_method() # Output: Dynamic class method called with value: 20
Summary
- Dynamic (Instance) Methods: Methods defined within a class that operate on instances of the class, taking
self
as the first parameter. - Static Methods: Methods that do not take
self
orcls
as parameters, defined with the@staticmethod
decorator. - Class Methods: Methods that take
cls
as the first parameter, defined with the@classmethod
decorator. - Dynamic Addition: Both instance methods and class methods can be added dynamically at runtime, showcasing Python's dynamic capabilities.