1. Using Python Mixins to Extend Classes
In Python, the standard way to share behavior across classes is through multiple inheritance using mixins. If you want a class to inherit class-level methods (or static methods), you can define them inside a mixin class and inherit from it.
# 1. Define a mixin class with class methods
class GreeterMixin:
@classmethod
def say_hello(cls):
return f"Hello from {cls.__name__}!"
# 2. Inherit from the mixin
class MyClass(GreeterMixin):
pass
# Usage
print(MyClass.say_hello())
# Output: Hello from MyClass!
2. Using an instance method in a mixin class example
# 1. Define a mixin class with an instance method
class GreeterMixin:
def say_hello(self):
return f"Hello, my name is {self.name}!"
# 2. Inherit from the mixin in your class
class User(GreeterMixin):
def __init__(self, name):
self.name = name
# --- Usage ---
user = User("Alice")
print(user.say_hello())
# Output: Hello, my name is Alice!
3 'Monkey Patching' example
# Original class
class Calculator:
def add(self, a, b):
return a + b
# Monkey-patched function
def multiply(self, a, b):
return a * b
# Patching the class at runtime
Calculator.multiply = multiply
calc = Calculator()
print(calc.multiply(3, 4)) # 12 (dynamically added method)
@classmethod
def add(cls, a, b):
print(cls) # <class '__main__.Calculator'>
return a + b
Calculator.add = add
print(Calculator.add(3, 4)) # 7
print(calc.add(3, 4)) # 7. Calculator.add is a class method, so it can be called on the instance as well