Chinaunix首页 | 论坛 | 博客
  • 博客访问: 490251
  • 博文数量: 74
  • 博客积分: 750
  • 博客等级: 军士长
  • 技术积分: 1453
  • 用 户 组: 普通用户
  • 注册时间: 2012-08-29 15:59
文章分类
文章存档

2014年(30)

2013年(8)

2012年(36)

分类: Python/Ruby

2012-10-23 10:01:00

复制代码
>>> class a: ... foo=100 ... >>> dir(a) ['__doc__', '__module__', 'foo'] >>> vars(a) {'__module__': '__main__', 'foo': 100, '__doc__': None} >>> b=a() >>> dir(b) ['__doc__', '__module__', 'foo'] >>> vars(b) {}
复制代码

上面看出,经典类a中貌似没有__dict__属性。为什么可以作为vars()函数的参数呢?


>>> vars(1) Traceback (most recent call last): File "", line 1, in TypeError: vars() argument must have __dict__ attribute

提示必须有__dict__属性。

 

下面看出:dir的参数是新式类或其对象时,返回值包括__dict__属性。

复制代码
>>> class c(object): ... foo=200 ... >>> dir(c) ['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'foo'] >>> vars(c) dict_proxy({'__dict__': '__dict__' of 'c' objects>, '__module__': '__main__', 'foo': 200, '__weakref__': '__weakref__' of 'c' objects>, '__doc__': None}) >>> d=c() >>> dir(d) ['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'foo'] >>> vars(d) {}
复制代码

>>> c.__dict__ dict_proxy({'__dict__': '__dict__' of 'c' objects>, '__module__': '__main__', 'foo': 200, '__weakref__': '__weakref__' of 'c' objects>, '__doc__': None}) >>> d.__dict__ {}
>>> a.__dict__ {'__module__': '__main__', 'foo': 100, '__doc__': None} >>> b.__dict__ {}
阅读(5428) | 评论(0) | 转发(0) |
0

上一篇:python中的type函数

下一篇:python之Tkinter

给主人留下些什么吧!~~