天天看點

python dir()和vars()的差別

dir():預設列印目前子產品的所有屬性,如果傳一個對象參數則列印目前對象的屬性

vars():預設列印目前子產品的所有屬性,如果傳一個對象參數則列印目前對象的屬性

vars():函數以字典形式傳回參數中每個成員的目前值,如果vars函數沒有帶參數,那麼它會傳回包含目前局部命名空間中所有成員的目前值的一個字典。

>>> help(vars)

Help on built-in function vars in module __builtin__:

vars(...)

    vars([object]) -> dictionary 

    Without arguments, equivalent to locals().

    With an argument, equivalent to object.__dict__.

dir()和vars()的差別就是:dir()隻列印屬性,vars()則列印屬性與屬性的值。

a='abcdefg'
class B():
    c='djfj'

print dir()
print vars()
print dir(B)
print vars(B)
           

結果:

['B', '__builtins__', '__doc__', '__file__', '__name__', '__package__', 'a']

{'a': 'abcdefg', 'B': <class __main__.B at 0x02A2DD88>, '__builtins__': <module '__builtin__' (built-in)>, '__file__': 'E:\\workspace\\python day03\\main\\test.py', '__package__': None, '__name__': '__main__', '__doc__': None}

['__doc__', '__module__', 'c']

{'__module__': '__main__', 'c': 'djfj', '__doc__': None}

>>> class C(object):
	    f=2

	
>>> dir(C)
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'f']
>>> vars(C)
dict_proxy({'__dict__': <attribute '__dict__' of 'C' objects>, '__module__': '__main__', '__weakref__': <attribute '__weakref__' of 'C' objects>, '__doc__': None, 'f': 2})
>>> C.__dict__
dict_proxy({'__dict__': <attribute '__dict__' of 'C' objects>, '__module__': '__main__', '__weakref__': <attribute '__weakref__' of 'C' objects>, '__doc__': None, 'f': 2})
>>> c=C()
>>> dir(c)
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'f']
>>> vars(c)
{}
>>> c.__dict__
{}
>>> 
           

(完)