CKTIS / Python
vars()
Com argumento obtém o `__dict__` do objeto.
Versão: Python 3.14; repository image, production runtime not attested
Sintaxe
vars()
vars(object, /)Com argumento obtém o __dict__ do objeto.
A instância normal expõe o seu dicionário ativo e acrescentar width com 6 faz com que box.width valha 6. Um inteiro não tem esse dicionário e gera TypeError. Uma classe fornece uma vista só de leitura.
Sem argumento vars atua como locals.
class Box: pass
b = Box()
d = vars(b)
d["width"] = 6
assert d is b.__dict__ and b.width == 6
assert type(vars(Box)).__name__ == "mappingproxy"
Exemplos
class Box:
pass
box = Box()
vars(box)["width"] = 6
print(box.width)
try:
vars(3)
except TypeError as error:
print(type(error).__name__)
Resultado
6 TypeError
Sem argumento vars atua como locals.