📜  Python中 dir() 和 vars() 的区别

📅  最后修改于: 2022-05-13 01:54:56.253000             🧑  作者: Mango

Python中 dir() 和 vars() 的区别

由于Python以属于各自对象的字典的形式存储它们的实例变量,因此dir()vars()函数都用于列出Python类的实例/对象的属性。尽管具有类似的实用程序,但这些功能具有重要的个人用例。
dir()函数:
此函数函数更多属性,因为它不限于实例。它也显示类属性。它还显示其祖先类的属性。
vars()函数:
该函数以字典的形式显示实例的属性。
下表提供了 var() 和 dir() 之间的一些显着差异:

vars()dir()
Returns a dictionary of objects of single class where usedReturns a dictionary of objects of single class where used and its base classes
It returns a dictionary corresponding to the current local symbol table when no argument is passedIt returns the list of names in the current local scope when passed no argument
It returns a dictionary corresponding to the object’s symbol table if a module, class or class instance object as argument (or anything else that has a __dict__ attribute) is passed.It attempt to return a list of valid attributes for that object when passed an argument
As instances builtin types do not have __dict__ attribute, it returns an Error when used in a built-in type instance.It can be used with all built-in types without error

示例 1:

Python3
vars(list).keys()


Python3
dir(list)


输出:

示例 2:

Python3

dir(list)

输出: