Python 是否可以使用super()的方法,否则会隐式使用该方法?

Python 是否可以使用super()的方法,否则会隐式使用该方法?,python,class,Python,Class,我想重写dict,这样修改一个键就可以在修改后将dict转储到pickle中 为此,我重写了\uuuu setitem\uuuu。代码如下: 如果空“缓存”(转储的pickle)不存在,则初始化它 或加载其内容(如果缓存存在) 修改\uuuuu setitem\uuuuu以添加转储 它很好用。但是,我需要说明的是,pickle.load()在构建dict时也使用了\uuuuuu setitem\uuuuuuuu,此时不应尝试将其转储到do磁盘(因为它实际上是从磁盘加载的)。我使用的解决方案看

我想重写
dict
,这样修改一个键就可以在修改后将
dict
转储到pickle中

为此,我重写了
\uuuu setitem\uuuu
。代码如下:

  • 如果空“缓存”(转储的pickle)不存在,则初始化它
  • 或加载其内容(如果缓存存在)
  • 修改
    \uuuuu setitem\uuuuu
    以添加转储
它很好用。但是,我需要说明的是,
pickle.load()
在构建dict时也使用了
\uuuuuu setitem\uuuuuuuu
,此时不应尝试将其转储到do磁盘(因为它实际上是从磁盘加载的)。我使用的解决方案看起来很糟糕

import pickle
import myconfig  # en extension of logging to format logs across my scripts via myconfig.log
import sys

class CachedDict(dict):
    def __init__(self, db="cache.pickle", **kwargs):
        super().__init__()
        self.db = db
        try:
            # load the axisting cache, if any
            with open(self.db, 'rb') as f:
                data = pickle.load(f)
            self.update(data)
        except FileNotFoundError:
            # failed to load the cache, create a new one
            myconfig.log.info("no cache {db} found, initializing".format(db=self.db))
            with open(self.db, 'wb') as f:
                pickle.dump(self, f)
        else:
            myconfig.log.info("loading from {db} cached dict {self}".format(self=self, db=self.db))

    def __setitem__(self, key, value):
        super().__setitem__(key, value)
        # dump cache
        myconfig.log.debug("updating dict {self} with {key}, {value}".format(self=self, key=key, value=value))
        # do not write the cache when called from __init__: we are populating the dict
        if sys._getframe(1).f_code.co_name != '__init__':
            try:
                with open(self.db, 'wb') as f:
                    pickle.dump(self, f)
            except Exception as e:
                myconfig.log.error("cannot update cache: {e}".format(e=e))


a = CachedDict("hello.pickle")
a['hello'] = 'world'
a[3] = 5
a['hello'] = 'wazaa'
myconfig.log.debug("final dict: {a}".format(a=a))
这个输出

2016-01-11 12:59:54,134 | DEBUG | scratch_48 | 25 | __setitem__ | updating dict {3: 5} with 3, 5
2016-01-11 12:59:54,134 | DEBUG | scratch_48 | 25 | __setitem__ | updating dict {3: 5, 'hello': 'wazaa'} with hello, wazaa
2016-01-11 12:59:54,136 | INFO | scratch_48 | 20 | __init__ | loading from hello.pickle cached dict {3: 5, 'hello': 'wazaa'}
2016-01-11 12:59:54,136 | DEBUG | scratch_48 | 25 | __setitem__ | updating dict {3: 5, 'hello': 'world'} with hello, world
2016-01-11 12:59:54,137 | DEBUG | scratch_48 | 25 | __setitem__ | updating dict {3: 5, 'hello': 'world'} with 3, 5
2016-01-11 12:59:54,138 | DEBUG | scratch_48 | 25 | __setitem__ | updating dict {3: 5, 'hello': 'wazaa'} with hello, wazaa
2016-01-11 12:59:54,139 | DEBUG | scratch_48 | 39 | <module> | final dict: {3: 5, 'hello': 'wazaa'}

有没有一种方法可以指导Python在这种情况下使用
super()
版本的
\uuuuu setitem\uuuuuuu

在dict更新并关闭文件后立即将数据写入文件, 如何防止使用多个线程调用此CachedAct,或者用户在两次调用pickle.dump的间隔内修改此CachedAct


你能不能在CachedDict中包装一个普通的dict,然后在显式调用CachedDict.close(或在_del___________________________________

class CachedDict(): def __store(self): try: with open(self.db, 'wb') as f: pickle.dump(self.__dict, f) except Exception as e: print "cannot update cache: {e}".format(e=e) def __init__(self, db="cache.pickle", **kwargs): self.__dict = {} self.db = db try: # load the axisting cache, if any with open(self.db, 'rb') as f: data = pickle.load(f) self.update(data) except: self.__store() def __setitem__(self, key, value): self.__dict[key] = value self.__store() def __str__(self): return self.__dict.__str__() 类CachedDict(): def____商店(自助): 尝试: 将open(self.db,'wb')作为f: pickle.dump(自存储,f) 例外情况除外,如e: 打印“无法更新缓存:{e}”。格式(e=e) def uuu init uuuu(self,db=“cache.pickle”**kwargs): self.\u dict={} self.db=db 尝试: #加载axisting缓存(如果有) 将open(self.db,'rb')作为f: 数据=pickle.load(f) 自我更新(数据) 除: 自助商店() 定义设置项(自身、键、值): self.\u dict[键]=值 自助商店() 定义(自我): 返回自我。_dict._str___;()
锁定是在代码中处理的——我给出了一个简单的例子来缩小到问题本身。我知道这种方法的种族条件。你有没有想过为你的案例设计一个装饰师?然后,您可以用它包装任何函数或方法调用。 class CachedDict(): def __store(self): try: with open(self.db, 'wb') as f: pickle.dump(self.__dict, f) except Exception as e: print "cannot update cache: {e}".format(e=e) def __init__(self, db="cache.pickle", **kwargs): self.__dict = {} self.db = db try: # load the axisting cache, if any with open(self.db, 'rb') as f: data = pickle.load(f) self.update(data) except: self.__store() def __setitem__(self, key, value): self.__dict[key] = value self.__store() def __str__(self): return self.__dict.__str__()