performan的不变对象设计

2024-06-25 23:57:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我的应用程序中需要很多小对象。它们必须是不可变的,并且在我设置新属性时返回一个新实例。在

我找到了很多方法来禁用obj.prop = newValue行为,现在我需要这样做:

newObj = obj.setTitle(title)
newObj = obj.setDirection(x, y)
newObj = obj.incrementCount()
newObj = obj.swap()

目前我这样做:

^{pr2}$

这个性能好吗?有没有更快的方法可以在某些属性发生更改的情况下返回对象的克隆?在

我使用__slots__。我的对象具有预定义的属性。我没有通用的.set(prop, value)方法

(欢迎使用Python 3.5+)


Tags: 对象实例方法obj应用程序属性titleswap
2条回答

{1}而不是使用^ 1>方法来获得不变性:

import collections as co

# this will create a class with five attributes
class Info(co.namedtuple('BaseInfo', 'x y a b c')):
    __slots__ = ()

    def setDirection(self, x, y):
        return self._replace(x=x, y=y)

    def swap(self):
        return self._replace(x=self.y, y=self.x)

我已经对这两个类中swap()方法的性能进行了基准测试,从namedtuple派生的类在Python3中大约快3-4倍。以下是基准代码:

^{pr2}$

结果:

Built from scratch
1.8578372709998803
Derived from namedtuple
0.520611657999325

通过为对象定义自定义复制方法,可以显著提高性能:

class Info(object):
    __slots__ = ['x', 'y', 'z']

    def swap(self):
        newObj = self.copy()
        newObj.x, newObj.y = self.y, self.x
        return newObj

    def copy(self):
        clone = type(self)()
        for slot in self.__slots__:
            if hasattr(self, slot):
                setattr(clone, slot, getattr(self, slot))
        return clone

测试:

^{pr2}$

结果:

copy.copy
1.5658336669985147
custom copy
0.4359149369993247

相关问题 更多 >