我的应用程序中需要很多小对象。它们必须是不可变的,并在设置新属性时返回新实例。性能不可变的对象设计
我找到了很多方法来禁用obj.prop = newValue
行为,现在我需要这样的:
newObj = obj.setTitle(title)
newObj = obj.setDirection(x, y)
newObj = obj.incrementCount()
newObj = obj.swap()
目前,我这样做:
class Info(object):
__slots__ = ['_x', '_y', ...]
def setDirection(self, x, y):
newObj = copy.copy(self) # shallow copy is OK
newObj._x = x
newObj._y = y
return newObj
def swap(self):
newObj = copy.copy(self)
# methods can do different things
newObj._x, newObj._y = self._y, self._x
return newObj
这是很好的性能比较方面?有没有更快的方法来返回一些属性更改的对象的克隆?我使用__slots__
。我的对象有预定义的属性。我有没有通用.set(prop, value)
方法
(Python的3.5+欢迎)
为什么你需要你的对象是不可变的?在OOP中,对象应该是可变的。如果你想要不变性,类和对象不是你正在寻找的数据结构。你可能会做一些metaclass hack来使它工作,但你不会保证不可变性或者获得不可变数据类型的任何好处。 –
有一些有趣的项目向python引入了持久性/不可变性/功能性数据结构。你可以看看它是如何完成的,例如“pyrsistent”:https://github.com/tobgu/pyrsistent –