cao627 发表于 2014-04-27 18:31

求助:《Dive Into Python》中的一个列子是不是错了?

本帖最后由 cao627 于 2014-04-27 18:32 编辑

在《Dive Into Python》http://woodpecker.org.cn/diveintopython/object_oriented_framework/userdict.html的5.5节有个列子如下:class UserDict:                              
    def __init__(self, dict=None):            
      self.data = {}                        
      if dict is not None: self.update(dict)不太理解

感觉最后一句应该这样:
if dict is not None: self.data.update(dict)

cao627 发表于 2014-04-27 20:27

知道是怎么回事了
此处的update函数不是 字典这个内置数据类型update方法。而是UserDict这个模块中class UserDict中定义的方法。其内容为:def update(self, dict=None, **kwargs):
      if dict is None:
            pass
      elif isinstance(dict, UserDict):
            self.data.update(dict.data)
      elif isinstance(dict, type({})) or not hasattr(dict, 'items'):
            self.data.update(dict)
      else:
            for k, v in dict.items():
                self = v
      if len(kwargs):
            self.data.update(kwargs)
页: [1]
查看完整版本: 求助:《Dive Into Python》中的一个列子是不是错了?