class Foo(object):
bar = {'a': None, 'b': None}
def do_something(self):
print self.bar['a']
self.bar['a'] = 12
我想做的是:
从self.bar[xxx]
读取时,我得到了真正的价值
写入self.bar[xxx]
时,请致电制定者进行真实设置。
这是一个真实世界的例子:
class VoteMixin(object):
self._vote_nums = {'up': None, 'down': None}
def fetch_from_db(self):
self._vote_nums = {} # set with values read from db
@property
def up_vote_nums(self):
if self._vote_nums['up'] is None:
self.fetch_from_db()
return self._vote_nums['up']
@property
def down_vote_nums(self):
# the same
pass
def up_vote(self):
# update to db
if self.vote_nums['up'] is None:
self.fetch_from_db()
self._vote_nums['up'] += 1
def down_vote(self):
# update to db
if self.vote_nums['down'] is None:
self.fetch_from_db()
self._vote_nums['down'] += 1
问题是,我不想在每次写入时都检查self._vote_nums['up or down']
是否为无。