python 元程式設計是一種高階程式設計技術,允許開發者在執行時修改 Python 程式碼本身。這為 Python 帶來了強大的靈活性和動態性,使其成為建立複雜和可擴展應用程式的理想選擇。
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 元程式設計為開發者提供了強大的工具,使他們能夠創建動態、靈活且可擴展的應用程式。透過理解並熟練運用元程式技術,開發者可以將 Python 的功能發揮到極致。
以上是踏入Python元程式設計之旅:無限魔力的探索的詳細內容。更多資訊請關注PHP中文網其他相關文章!