📅  最后修改于: 2023-12-03 15:19:02.162000             🧑  作者: Mango
在Python中,vars()函数可以返回对象的__dict__属性值。如果没有提供参数,它返回当前作用域中的变量和值的字典。如果提供一个对象作为参数,它返回该对象的属性字典。
vars([object])
vars()函数返回对象的属性字典,如果没有提供对象参数,则返回当前本地作用域中的变量和值的字典。
示例1:返回当前本地作用域中的变量和值的字典。
def hello():
name = "world"
print(vars())
hello()
# Output: {'name': 'world'}
示例2:返回一个实例对象的属性字典。
class MyClass:
def __init__(self):
self.var1 = "Hello"
self.var2 = "World"
myObj = MyClass()
print(vars(myObj))
# Output: {'var1': 'Hello', 'var2': 'World'}
示例3:返回一个模块对象的属性字典。
import math
print(vars(math))
# Output: 字典类型,包含了 math 模块中所有的变量名和对应的值。
vars()函数只能返回拥有__dict__属性的对象的属性字典。如果在实例中定义了__slots__属性,则vars()函数不能返回对象的属性字典。如果尝试在类中使用__slots__属性,则必须明确定义__dict__属性。