Home > Article > Backend Development > A journey into Python metaprogramming: the exploration of infinite magic
python MetaProgramming is an advanced programming technique that allows developers to modify the Python code itself at runtime. This brings great flexibility and dynamism to Python, making it ideal for building complex and scalable applications.
class Meta(type): def __new__(cls, name, bases, attrs): attrs["new_attr"] = "new value" return super().__new__(cls, name, bases, attrs) class MyClass(metaclass=Meta): pass obj = MyClass() print(obj.new_attr)# Output: "new value"
def create_class(name, bases, attrs): return type(name, bases, attrs) def create_instance(cls, *args, **kwargs): obj = cls.__new__(cls) cls.__init__(obj, *args, **kwargs) return obj MyClass = create_class("MyClass", (), {}) obj = create_instance(MyClass)
class MyClass: def __init__(self, name): self.name = name def greet(self): print(f"Hello, {self.name}!") def modify_class(cls): cls.new_attr = "new value" def new_greet(self): print(f"Modified greeting: {self.name}!") cls.greet = new_greet modify_class(MyClass) obj = MyClass("John") obj.greet()# Output: "Modified greeting: John!"
def log_method_calls(cls): def wrapper(self, *args, **kwargs): print(f"Calling method {self.__class__.__name__}.{self.__class__.__qualname__}") return cls.__call__(self, *args, **kwargs) cls.__call__ = wrapper return cls @log_method_calls class MyClass: def __init__(self, name): self.name = name def greet(self): print(f"Hello, {self.name}!") obj = MyClass("John") obj.greet()# Output: "Calling method MyClass.MyClass"
class Proxy(object): def __init__(self, obj): self._obj = obj def __getattr__(self, name): return getattr(self._obj, name) def __setattr__(self, name, value): setattr(self._obj, name, value) class MyClass: def __init__(self, name): self.name = name def greet(self): print(f"Hello, {self.name}!") obj = MyClass("John") proxy = Proxy(obj) proxy.greet()# Output: "Hello, John!"
Python metaprogramming provides developers with powerful tools that enable them to create dynamic, flexible, and scalable applications. By understanding and proficiently using metaprogramming techniques, developers can maximize the capabilities of Python.
The above is the detailed content of A journey into Python metaprogramming: the exploration of infinite magic. For more information, please follow other related articles on the PHP Chinese website!