xinhu1300 发表于 2015-4-28 09:27:04

关于python中vars()的疑惑

  在python核心编程第二版写到vars()内建函数调用时,参数必须有一个__dict__属性.



>>> 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__': , '__module__': '__main__', 'foo': 200, '__weakref__': , '__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__': , '__module__': '__main__', 'foo': 200, '__weakref__': , '__doc__': None})
>>> d.__dict__
{}


>>> a.__dict__
{'__module__': '__main__', 'foo': 100, '__doc__': None}
>>> b.__dict__
{}
  但实际上: 经典类或其对象也包括了__dict__属性。
  疑惑:难道dir()函数的参数是经典类时,返回的列表不包含__dict__属性?who can tell me?
页: [1]
查看完整版本: 关于python中vars()的疑惑