快速劈:
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
你想在這裏完成什麼?爲什麼'foo.version()'改變了? – mgilson
我認爲通過重寫'__setattr__'和'__delattr__'可以在調用時增加每個實例的計數器來實現接近此目的。但是,我很難想到這種情況真的很有用。 – senderle
@mgilson因爲從版本1開始的'foo'已經更改了3次。 – Srg