vars()
方法返回给定对象的 __dict__
(字典映射)属性。
示例
# returns __dict__ of a list
print(vars(list))
# Output:
# {'__repr__': <slot wrapper '__repr__' of 'list' objects>, '__hash__': None, '__getattribute__': <slot wrapper '__getattribute__' of 'list' objects>, ….}
vars() 语法
vars()
方法的语法是
vars(object)
vars() 参数
vars()
方法接受一个参数
- 对象 - 可以是模块、类、实例或任何具有
__dict__
属性的对象
vars() 返回值
vars()
方法返回
- 给定对象的
__dict__
属性。 - 不传递参数时,返回局部作用域中的方法
- 如果传递的对象没有
__dict__
属性,则返回 TypeError
示例:Python vars()
# vars() with no argument
print (vars())
# returns __dict__ of a dictionary object
print(vars(dict))
输出
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>} {'__repr__': <slot wrapper '__repr__' of 'dict' objects>, '__hash__': None, '__getattribute__': <slot wrapper '__getattribute__' of 'dict' objects> ….}
示例 2:vars() 没有 __dict__ 属性参数
string = "Jones"
# vars() with a string
print(vars(string))
输出
TypeError: vars() argument must have __dict__ attribute
在上面的示例中,我们向 vars()
方法传递了一个字符串 "Jones"
。
由于字符串没有 __dict__
属性,我们得到了 TypeError。
示例 3:带自定义对象的 vars()
class Fruit:
def __init__(self, apple = 5, banana = 10):
self.apple = apple
self.banana = banana
eat = Fruit()
# returns __dict__ of the eat object
print(vars(eat))
输出
{'apple': 5, 'banana': 10}
在上面的示例中,我们使用了 vars()
方法和一个自定义对象,即 Fruit
类的 eat。
如您所见,Fruit
类中有两个变量 apple 和 banana,它们的值分别为 5 和 10。
因此,由于 vars()
方法,我们得到了字典形式的输出 {'apple': 5, 'banana': 10}。
另请阅读