python中的透明对象版本化
我想在不知道它的情况下版本化对象。python中的透明对象版本化
事情是这样的:
class Versioned(object): ...
def version(self):
...
class Foo(Versioned):
def __init__(self, a):
self.a = a
foo = Foo(123)
assert foo.version() == 1
foo.a = 1
foo.a = 2
foo.a = 3
assert foo.version() == 4
是否有这样做的一个简单的方法?
回答:
class Versioned(object): def __init__(self):
self.version = 0
def __setattr__(self, name, value):
if name == 'version':
object.__setattr__(self, 'version', value)
else:
object.__setattr__(self, name, value)
object.__setattr__(self, 'version', self.version +1)
例子:
class Foo(Versioned): pass
f = Foo()
print f.version # prints 0
f.a = 1
print f.version # prints 1
f.b = 3
print f.version # prints 2
f.b = 33
print f.version # prints 3
回答:
快速劈:
class Versioned(object): version = 0
def __init__(self):
self.version = 0
def _increaseVersion(self):
super(Versioned, self).__setattr__('version', self.version+1)
def __setattr__(self, attr, value):
super(Versioned, self).__setattr__(attr, value)
self._increaseVersion()
def __delattr__(self, attr):
super(Versioned, self).__delattr__(attr)
self._increaseVersion()
class Foo(Versioned):
def __init__(self, a):
self.a = a
super(Foo, self).__init__()
foo = Foo(123)
print 'value:', foo.a
print 'version:', foo.version
foo.a = 23
print 'value:', foo.a
print 'version:', foo.version
del foo.a
print hasattr(foo, 'a')
print 'version:', foo.version
输出:
value: 123 version: 1
value: 23
version: 2
False
version: 3
回答:
请看看https://github.com/swisscom/cleanerversion。如果我正确理解你的要求,它确实正是你要找的。
由于我们需要一个持久的解决方案,因此该模块在Django上构建,允许将这些对象写入任何Django支持的关系数据库。
以上是 python中的透明对象版本化 的全部内容, 来源链接: utcz.com/qa/265597.html