在 Python 中,魔法办法是指那些以双下划线结尾和结尾的非凡办法。它们是 Python 的内置办法,对应于 Python 对象的各种运算符。通过实现这些魔法办法,咱们能够扭转 Python 对象的行为。这篇文章将深入探讨 Python 的一些魔法办法,并通过示例展现如何应用它们。
一、结构和初始化
__new__
和 __init__
是 Python 对象生命周期的开始。__new__
办法是在一个对象实例化的时候所调用的第一个办法,在调用 __init__
初始化前,先调用 __new__
。
class MyClass: def __new__(cls, *args, **kwargs): print('Instance is created') instance = super().__new__(cls) return instance def __init__(self, name): print('Instance is initialized') self.name = nameobj = MyClass('MyClass') # 输入:Instance is created Instance is initialized
二、字符串示意
__str__
和 __repr__
都是用于显示的魔法办法。__str__
是敌对易读的形式出现,而 __repr__
是精确、无歧义地表达出来,次要供开发和调试时应用。
class MyClass: def __init__(self, name): self.name = name def __str__(self): return f'Instance of MyClass with name {self.name}' def __repr__(self): return f'MyClass(name={self.name})'obj = MyClass('MyClass')print(str(obj)) # 输入:Instance of MyClass with name MyClassprint(repr(obj)) # 输入:MyClass(name=MyClass)
三、算术运算符
魔法办法还能够用来定义对象的算术运算行为,例如 __add__
、__sub__
、__mul__
等。
class Number: def __init__(self, value): self.value = value def __add__(self, other): return self.value + other.valuenum1 = Number(1)num2 = Number(2)print(num1 + num2) # 输入:3
四、比拟运算符
比拟运算符的魔法办法包含 __lt__
、__le__
、__eq__
、__ne__
、__gt__
、__ge__
等。
class Number: def __init__(self, value): self.value = value def __lt__(self, other): return self.value < other.valuenum1 = Number(1)num2 = Number(2)print(num1 < num2) # 输入:True
五、属性拜访
当咱们试图拜访一个对象的属性时,__getattr__
、__setattr__
、__delattr__
和 __getattribute__
魔法办法就会被调用。__getattribute__
办法是用于获取一个属性的值,而 __setattr__
是在咱们试图设置一个属性值时被调用。
class MyClass: def __init__(self): self.name = 'MyClass' def __getattribute__(self, item): if item == 'name': print('Accessing name attribute') return object.__getattribute__(self, item) def __setattr__(self, key, value): print(f'Setting attribute {key} with value {value}') self.__dict__[key] = valueobj = MyClass()print(obj.name) # 输入:Accessing name attribute MyClassobj.name = 'New name' # 输入:Setting attribute name with value New name
六、上下文管理器
上下文管理器是通过 __enter__
和 __exit__
魔法办法实现的,它们通常在 with
语句中应用。
class ManagedFile: def __init__(self, filename): self.filename = filename def __enter__(self): self.file = open(self.filename, 'r') return self.file def __exit__(self, exc_type, exc_val, exc_tb): if self.file: self.file.close()with ManagedFile('hello.txt') as f: content = f.read()print(content)
在这个例子中,__enter__
办法关上文件并返回,__exit__
办法在来到 with
块时被调用,负责敞开文件。
七、论断
Python 的魔法办法为咱们提供了扭转对象行为的弱小工具,让咱们可能以合乎 Python 格调的形式去操作和解决对象。同时,了解并把握这些魔法办法也是成为高级 Python 程序员的必经之路。