How to Use vars() Function in PythonPython Basics


The vars() function returns the object’s attributes names and values in the format of dictionary.

Example

#!/usr/bin/python3

print(vars())

print('nPrint out attributes of an object')
class Address:
  state = "California"
  zip = 95112
  city = "San Jose"

a = vars(Address)  # attributes of an object
print(a)  

Output:

{'__name__': '__main__', '__doc__': None, '__package__': None, 
'__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x7f619439e358>, 
'__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 
'signal': <module 'signal' from '/usr/local/lib/python3.6/signal.py'>, '__file__': 'main.py', '__cached__': None}

Print out attributes of an object
{'__module__': '__main__', 'state': 'California', 'zip': 95112, 'city': 'San Jose', 
'__dict__': <attribute '__dict__' of 'Address' objects>, '__weakref__': <attribute '__weakref__' of 'Address' objects>, '__doc__': None}

Syntax

vars(object)

Parameters

Name Description
object Can be module, class, instance, or any object having __dict__ attribute

Return Value

It returns the __dict__ attribute of the given object.

© 2024 Cheerlearn.com, all rights reserved. Privacy Policy | Contact Us