免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
12下一页
最近访问板块 发新帖
查看: 4171 | 回复: 10
打印 上一主题 下一主题

菜鸟问问题了 关于UserDict [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2012-06-13 15:15 |只看该作者 |倒序浏览
书中的一个例子:
  1. class UserDict:                                
  2.     def __init__(self, dict=None):            
  3.         self.data = {}                        
  4.         if dict is not None: self.update(dict)
复制代码
本地试了一下:
>>> dict = UserDict({'a':'b','c':'d'})
>>> dict
{'a': 'b', 'c': 'd'}
>>> dict.data
{'a': 'b', 'c': 'd'}

继续往下看:
  1.    
  2.     def clear(self): self.data.clear()         
  3.     def copy(self):                             
  4.         if self.__class__  is UserDict:         
  5.             return UserDict(self.data)         
  6.         import copy                             
  7.         return copy.copy(self)                 
  8.     def keys(self): return self.data.keys()     
  9.     def items(self): return self.data.items()  
  10.     def values(self): return self.data.values()
复制代码
我的疑问是:
1.self.data存在的意义是什么?
为何返回的都是 self.data,小弟认为返回 self.clear()(举例),也没错啊?
2.>>> dict
{'a': 'b', 'c': 'd'}
>>> dict = UserDict({'a':'b','c':'d'})

dict是从哪里返回的?


谢谢谢谢。

论坛徽章:
0
2 [报告]
发表于 2012-06-13 15:39 |只看该作者
我好像有点明白了 self其实是一个对象(实例),self.data是一个字典。
但是我还是不很明白我的第二个问题。

论坛徽章:
0
3 [报告]
发表于 2012-06-13 15:50 |只看该作者
01.class UserDict:                                

02.    def __init__(self, dict=None):            

03.        self.data = {}                        

04.        if dict is not None: self.update(dict)
还是这段没看明白、
1。self我的理解应该是一个对象,self.update(dict)是什么意思呢 我在手册上只看到dict的方法呀。
2.self.data = {}  
为什么 会出现如下这种情况呢?
>>> dict = UserDict({'a':'b','c':'d'})
>>> dict.data
{'a': 'b', 'c': 'd'}

论坛徽章:
0
4 [报告]
发表于 2012-06-13 16:01 |只看该作者
打开自带的帮助文档,索引里输入dict,打开built-in class链接,里面有说明,你贴的内容对吗?
变量之类的不要跟保留关键字相同吧

论坛徽章:
0
5 [报告]
发表于 2012-06-13 23:45 |只看该作者
回复 3# fzc115100


01.class UserDict:                                

02.    def __init__(self, dict=None):            

03.        self.data = {}                        

04.        if dict is not None: self.update(dict)
还是这段没看明白、
1。self我的理解应该是一个对象,self.update(dict)是什么意思呢 我在手册上只看到dict的方法呀。
我感觉这里应该是slef.data.update(dict),也就是根据传入的字典参数,更新实例的属性data
2.self.data = {}  
为什么 会出现如下这种情况呢?
>>> dict = UserDict({'a':'b','c':'d'})
这里的dict是一个类的实例,如果直接命令行执行,应该是要调用__repr__()函数。
看楼主的执行结果,应该是在类中重新了此方法。

>>> dict.data
{'a': 'b', 'c': 'd'}

论坛徽章:
0
6 [报告]
发表于 2012-06-14 15:19 |只看该作者
kingsuper_ 发表于 2012-06-13 23:45
回复 3# fzc115100

真的非常感谢。
完全正确!
厉害厉害!
    def __repr__(self): return repr(self.data)

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[k] = v
        if len(kwargs):
            self.data.update(kwargs)
都如ls所说!

还想请教一个问题:
上面这段代码 您觉得在那种情况下会进入:
        else:
            for k, v in dict.items():
                self[k] = v
里面呢?
我觉得好像只能进入        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)
以上三种情况!
谢谢

论坛徽章:
0
7 [报告]
发表于 2012-06-14 16:09 |只看该作者
回复 6# fzc115100


    不知道你看的这段代码的语境是什么样,我猜想应该是这样的情况。

        else:
            for k, v in dict.items():
                self[k] = v

  如果dict.items()返回的是一个通过zip()合并的一个列表,例如:[('a',1),('b',1)]。
  这样的话这个dict也许是一个类的实例,且编写了items方法,返回这样的一个列表。

  这个要具体的来看这段代码,在书中的说明。
  
这段代码中,self[k] =v,按理来说类是不能这样操作的。或者说是self.data[k]=v?
还是说UserDict继承了dict?

论坛徽章:
0
8 [报告]
发表于 2012-06-14 16:16 |只看该作者
回复 6# fzc115100


    补充一点,你写的这个类,items方法,调用了data.items(),字典的items()方法,就会返回一个这样的列表。[('a', 1), ('b', 2)]
                     也就是说,如果存在另外一个类,和UserDict类似,也实现了一样的items方法,例如AnotherDict,那么:
                       test = AnotherDict()  
                       update(test)
                      就会进入这个条件了。

论坛徽章:
0
9 [报告]
发表于 2012-06-14 16:36 |只看该作者
回复 8# kingsuper_
精彩,我看懂了。
对于这个例子目前没有其他问题了。


其实这个例子就是python的一个自带模块
您在python*.*/LIb 下面应该可以找到UserDict.py的文件,在这个里面。

真是太感谢了!


   

论坛徽章:
0
10 [报告]
发表于 2012-06-14 16:54 |只看该作者
回复 8# kingsuper_
最后一个问题:
    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[k] = v
        if len(kwargs):
            self.data.update(kwargs)
是否可以改成:

    def update(self, dict=None, **kwargs):
        if dict is None:
            pass
        else:
            self.data.update(dict)
        if len(kwargs):
            self.data.update(kwargs)

我觉得是可以的:
update([other])
Update the dictionary with the key/value pairs from other, overwriting existing keys. Return None.

update() accepts either another dictionary object or an iterable of key/value pairs (as tuples or other iterables of length two).If keyword arguments are specified, the dictionary is then updated with those key/value pairs: d.update(red=1, blue=2).

想请教一下:没有这么做的目的是?因为效率?或者?







   
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP