python中的透明对象版本控制

时间:2012-10-26 11:56:24

标签: python versioning

我想在没有他们知道的情况下对对象进行版本化。

这样的事情:

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

有一种简单的方法吗?

3 个答案:

答案 0 :(得分:2)

快速入侵:

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

答案 1 :(得分:1)

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

答案 2 :(得分:0)

请看一下https://github.com/swisscom/cleanerversion。如果我正确地理解了您的要求,它就会完全符合您的要求。

由于我们需要一个有点持久的解决方案,该模块在Django上构建,允许将这些对象写入任何Django支持的关系数据库。