@dataclass
class Point:
x: int
y: int
z: int
这是一个dataclass, 它可以快速定义一个Point(x, y, z)的对象.
class Point:
def __init__(self, x: int, y: int, z: int):
self.x = x
self.y = y
self.z = z
相比这样一个对象, 必须要承认, dataclass确实很优雅.
那么, dataclass的性能如何?
实际上并不比普通对象高多少, 只能是接近于持平, 有些时候会出乎意料的慢.
但与__ slots __
搭配, 性能就很优秀了.
@dataclass
class Point:
x: int
y: int
z: int
__slots__ = ("x", "y", "z")
哦, 这样好丑, 定义slots是个非常恶心的过程
让我们写个自动添加slots的元类
class AutoSlotsMeta(type):
def __new__(mcs, *args, **kwargs):
if args[0] != "AutoSlots":
args[2]["__slots__"] = tuple([k for k in args[2].get("__annotations__").keys()])
return super().__new__(mcs, *args, **kwargs)
class AutoSlots(metaclass=AutoSlotsMeta):
pass
我们直接继承AutoSlots, 就可以自动根据字段添加slots
@dataclass
class Point(AutoSlots):
x: int
y: int
@dataclass
class Point2(Point):
z: int
一个性能不错, 定义清晰的dataclass就完成了
value = Point(10, 20, 30)
match value:
case Point(x=10 as x, y=20, z=30):
print(f"point x is {x}")
搭配3.10的match, 会有非常不错的体验
网友评论