Python vars() 函数



**Python vars() 函数** 是一个 内置函数,它返回关联对象的 **__dict__** 属性。此属性是一个字典,包含对象的所有可变属性。我们也可以说此函数是访问对象属性的字典格式的一种方式。

如果我们在不带任何参数的情况下调用 **vars()** 函数,则它的作用类似于 locals() 函数,并将返回一个包含局部符号表的字典。

始终记住,每个 Python 程序都具有一个符号表,其中包含有关程序中定义的名称(变量函数、类等)的信息。

语法

Python **vars()** 函数的语法如下所示:

vars(object)

参数

Python **vars()** 函数接受单个参数:

  • **object** - 此参数表示具有 __dict__ 属性的对象。它可以是模块、类或实例。

返回值

Python **vars()** 函数返回指定大小的 __dict__ 属性。如果未传递任何参数,则它将返回局部符号表。并且,如果传递的对象不支持 __dict__ 属性,则它会引发 TypeError 异常。

vars() 函数示例

练习以下示例以了解 Python 中 **vars()** 函数的用法

示例:vars() 函数的用法

在用户定义的类上应用 **vars()** 函数时,它会返回该类的属性。在下面的示例中,我们定义了一个类和一个具有三个属性的方法。并且,我们使用 **vars()** 函数显示它们。

class Vehicle:
   def __init__(self, types, company, model):
      self.types = types
      self.company = company
      self.model = model
        
vehicles = Vehicle("Car", "Tata", "Safari")
print("The attributes of the Vehicle class: ")
print(vars(vehicles))

当我们运行上述程序时,它会产生以下结果:

The attributes of the Vehicle class: 
{'types': 'Car', 'company': 'Tata', 'model': 'Safari'}

示例:使用内置模块的 vars() 函数

如果我们对一个内置模块使用**vars()**函数,它将显示该模块的描述。在下面的代码中,我们导入了字符串方法,并在**vars()**的帮助下,列出了该模块的详细描述。

import string
attr = vars(string)
print("The attributes of the string module: ", attr)

以下是上述代码的输出:

The attributes of the string module:  {'__name__': 'string', '__doc__': 'A collection of string constants......}

示例:使用vars()获取用户定义函数的属性

在下面的示例中,我们创建了一个名为“newFun”的用户定义方法,并尝试使用**vars()**函数显示其属性。

def newFun():
   val1 = 10
   val2 = 20
   print(vars())

print("The attributes of the defined function:")
newFun()

上述代码的输出如下:

The attributes of the defined function:
{'val1': 10, 'val2': 20}
python_built_in_functions.htm
广告

© . All rights reserved.