Table of Contents
The vars() function returns the __dict__ attribute of the given object.
The syntax of the vars() function is:
vars(object)
1. vars() Parameters
vars() takes a maximum of one parameter.
- object – can be module, class, instance, or any object having the
__dict__attribute.
2. Return Value from vars()
vars()returns the__dict__attribute of the given object.- If the object passed to
vars()doesn’t have the__dict__attribute, it raises aTypeErrorexception. - If no argument is passed to
vars(), this function acts like locals() function.
Note: __dict__ is a dictionary or a mapping object. It stores object’s (writable) attributes.
3. Example: Working of Python vars()
class Foo:
def __init__(self, a = 5, b = 10):
self.a = a
self.b = b
object = Foo()
print(vars(object))
Output
{'a': 5, 'b': 10}
Also, run these statements on Python shell:
>>> vars(list)
>>> vars(str)
>>> vars(dict)
Related posts:
Python Objects and Classes
Python next()
Python Program to Copy a File
Python hasattr()
Python eval()
Python List sort()
Python Program to Sort a Dictionary by Value
Python format()
Python Program to Check if a Number is Odd or Even
Natural Language Processing with Python - Steven Bird & Ewan Klein & Edward Loper
Python String split()
Python Program to Get the Class Name of an Instance
Python Program to Randomly Select an Element From the List
Python complex()
Python Program to Catch Multiple Exceptions in One Line
Python Set pop()
Python Program to Find Factorial of Number Using Recursion
Python frozenset()
Python Program to Create a Long Multiline String
Python List clear()
Python String join()
Python String rstrip()
Python time Module
Python List insert()
Python Program to Find the Size (Resolution) of a Image
Python open()
Python File I/O Operation
Python slice()
Python Set update()
Python String startswith()
Python Program to Print Output Without a Newline
Applied Text Analysis with Python - Benjamin Benfort & Rebecca Bibro & Tony Ojeda