Python测试开发基础(一)
常见的魔术方法
Python 中的魔术方法(也称为“特殊方法”或“dunder 方法”,因为它们以双下划线 __
开头和结尾)是 Python 提供的一种让类可以与 Python 内置操作(如运算符、函数调用、内置函数等)互动的机制。魔术方法使得 Python 的类更加灵活和强大。
常见的魔术方法分类及其用途
1. 初始化与表示
-
__init__(self, ...)
:构造方法,用于初始化对象。在创建对象时自动调用。class MyClass:def __init__(self, name):self.name = name
-
__str__(self)
:定义对象的“可打印”字符串表示,用于print()
或str()
函数。class MyClass:def __str__(self):return f"MyClass with name {self.name}"
-
__repr__(self)
:定义对象的正式字符串表示,用于repr()
函数和调试,通常返回一个可以用来重建对象的字符串。class MyClass:def __repr__(self):return f"MyClass({self.name!r})"
2. 算术运算符重载
-
__add__(self, other)
:加法运算符+
。 -
__sub__(self, other)
:减法运算符-
。 -
__mul__(self, other)
:乘法运算符*
。 -
__truediv__(self, other)
:除法运算符/
。 -
__floordiv__(self, other)
:整除运算符//
。 -
__mod__(self, other)
:取模运算符%
。 -
__pow__(self, other)
:指数运算符**
。 -
__radd__(self, other)
:反向加法运算,用于支持other + self
这样的操作。
class MyNumber:def __init__(self, value):self.value = valuedef __add__(self, other):return MyNumber(self.value + other.value)
3. 比较运算符重载
-
__eq__(self, other)
:相等运算符==
。 -
__ne__(self, other)
:不相等运算符!=
。 -
__lt__(self, other)
:小于运算符<
。 -
__le__(self, other)
:小于等于运算符<=
。 -
__gt__(self, other)
:大于运算符>
。 -
__ge__(self, other)
:大于等于运算符>=
。
class MyNumber:def __eq__(self, other):return self.value == other.value
4. 容器相关的魔术方法
-
__len__(self)
:用于len()
函数,返回对象的长度。 -
__getitem__(self, key)
:用于索引操作,如obj[key]
。 -
__setitem__(self, key, value)
:用于赋值操作,如obj[key] = value
。 -
__delitem__(self, key)
:用于删除操作,如del obj[key]
。 -
__iter__(self)
:使对象可迭代,返回一个迭代器。 -
__next__(self)
:定义迭代器的下一步,用于next()
函数。
class MyList:def __init__(self, items):self.items = itemsdef __len__(self):return len(self.items)def __getitem__(self, index):return self.items[index]def __setitem__(self, index, value):self.items[index] = valuedef __delitem__(self, index):del self.items[index]def __iter__(self):return iter(self.items)
5. 对象生命周期
-
__new__(cls, ...)
:用于创建对象实例,通常与__init__
配合使用,尤其在继承场景中。 -
__del__(self)
:析构方法,在对象被垃圾回收前调用,类似于 C++ 中的析构函数。
class MyClass:def __new__(cls):print("Creating instance")return super().__new__(cls)def __del__(self):print("Instance is being destroyed")
6. 上下文管理
-
__enter__(self)
:进入上下文管理器,用于with
语句。 -
__exit__(self, exc_type, exc_value, traceback)
:退出上下文管理器,处理异常。
class MyContextManager:def __enter__(self):print("Entering context")return selfdef __exit__(self, exc_type, exc_value, traceback):print("Exiting context")with MyContextManager():print("Inside context")
7. 其他魔术方法
-
__call__(self, *args, **kwargs)
:使对象可调用,像函数一样调用对象。 -
__bool__(self)
:定义对象的布尔值转换,用于bool()
函数和条件判断。 -
__hash__(self)
:定义对象的哈希值,使对象可用作字典键或存入集合。 -
__contains__(self, item)
:用于in
运算符,检查对象中是否包含某个元素。
class MyCallable:def __call__(self, *args, **kwargs):print("Called with", args, kwargs)obj = MyCallable()obj(1, 2, key='value')
总结
魔术方法使得 Python 的类非常灵活,可以轻松地与 Python 的内置操作集成。通过定义这些方法,你可以定制类的行为,使其更符合你的需求,从而创建更强大的类和数据结构。