实现Python的Magic方法可以实现很多神奇的功能
import time
class SortedObj(object):
"""
借助实现一个可排序类,讲讲python的magic方法
"""
def __init__(self):
"""初始化方法"""
self.__created_at__ = time.time()
def __lt__(self, other: "SortedObj"):
"""
实现这个magic方法,该类的实列可以进行小于比较
"""
return self.__created_at__ < other.__created_at__
def __gt__(self, other: "SortedObj"):
"""
实现这个magic方法,该类的实列可以进行大于比较
"""
return self.__created_at__ > other.__created_at__
def __eq__(self, other: "SortedObj"):
"""
实现这个magic方法,该类的实列可以进行等于比较
ps: object 基础类实现了等于的magic方法,用于比较两个实例是否相等
所以正常情况下,不重载这个方法
"""
return self.__created_at__ == other.__created_at__
def __le__(self, other: "SortedObj"):
"""
实现这个magic方法,该类的实例可以进行小于等于(<=)比较
"""
return self.__created_at__ <= other.__created_at__
def __ge__(self, other: "SortedObj"):
"""
实现这个magic方法,该类的实例可以进行大于等于(>=)比较
"""
return self.__created_at__ >= other.__created_at__
class OtherMagic(object):
"""
其他部分magic方法
"""
def __init__(self, num=1):
self.num = 0 - num
self.lst = [1, 2, 3]
def __add__(self, other):
"""
该方法重载加法运算
"""
if isinstance(other, int):
self.num += other
elif isinstance(other, self.__class__):
self.num += other.num
return self
def __setattr__(self, key, value):
"""
该方法重载,实列属性赋值操作
"""
super(OtherMagic, self).__setattr__(key, value)
def __enter__(self):
"""
该方法实现 with 语法糖
"""
print('with enter')
return self
def __exit__(self, exc_type, exc_val, exc_tb):
"""
该方法实现 with 语法糖
"""
print('with exit')
def __setitem__(self, key, value):
"""
该方法实现字典形式的赋值操作
eg: obj['a'] = 'b'
print(obj.a) -> b
"""
setattr(self, key, value)
def __getitem__(self, item):
"""
该方法实现字典形式的取值
eg: print(obj['a']) -> b
"""
return getattr(self, item, None)
def __getattribute__(self, item):
"""
该方法hook实例属性的调用
"""
try:
return super(OtherMagic, self).__getattribute__(item)
except:
return self.__dict__.get(item)
def __call__(self, *args, **kwargs):
"""
该方法实现实例可调用
eg: obj() -> call me
"""
print('call me')
def __int__(self):
"""
该方法实现实例可被整数化
eg:int(obj)
"""
return self.num
def __iter__(self):
"""
该方法实现实例可以被循环读取
eg: for item in obj:
print(item)
"""
yield from self.lst
def __len__(self):
"""
该方法实现实例可以求长度
eg: len(obj)
"""
return self.num
def __abs__(self):
"""
该方法实现实例可求绝对值
eg: abs(obj)
"""
return abs(self.num)
def __and__(self, other):
"""
该方法实现实例与操作
eg: obj & 1
"""
return self.num & other
def __or__(self, other):
"""
该方法实现实例或操作
eg: obj | 1
"""
return self.num | other
def __bool__(self):
"""
该方法实现实例布尔化
eg: bool(obj)
"""
return self.num > 0
def __bytes__(self):
"""
该方法实现实例二进制化
eg: bytes(obj)
"""
return self.num.to_bytes(length=1, byteorder='big', signed=True)