{"@context":"https://schema.org","@type":"Article","mainEntityOfPage":{"@type":"WebPage","@id":"https://www.tutorialsteacher.com/python/vars-method"},"headline":"Python vars() Method","author":{"@type":"Organization","name":"TutorialsTeacher","url":"https://www.tutorialsteacher.com/aboutus"},"publisher":{"@type":"Organization","name":"TutorialsTeacher","logo":{"@type":"ImageObject","url":"https://www.tutorialsteacher.com/Content/images/logo.svg"},"sameAs":["https://www.facebook.com/tutorialsteacher","https://twitter.com/tutorialstchr","https://www.youtube.com/@tutorialsteacherOfficial"]},"dateModified":"2021-06-26T15:03:44.2391720Z","description":"The vars() method returns the __dict__ attribute of the specified object. A __dict__ object used to store an object's writable attributes."}__dict__ attribute of the specified object. A __dict__ object used to store an object's writable attributes." />

Python vars() Method

The vars() method returns the __dict__ attribute of the specified object. A __dict__ object is used to store an object's writable attributes.

vars() Syntax:

vars(object)

Parameters:

object: (Optional) An object having the __dict__ attribute.

Return Value:

Returns the __dict__ value.

The following example demonstrates the vars() method.

Example: vars()
class student:
    def __init__(self):
        self.name = ''
        self.age=0

std = student()
print(vars(std))

std.name = 'Bill'
std.age = 18
print(vars(std))
Output
{'name': '', 'age': 0}
{'name': 'Bill', 'age': 18}

The vars() method raises an error if the class of the specified object does not have the __dict__() method. For example, non of the built-in class implements it, so passing built-in objects to vars() will raise an error, as shown below.

Example: vars()
print(vars('Hello World')) # raises TypeError
print(vars(10)) # raises TypeError
Output
TypeError: vars() argument must have dict attribute
TypeError: vars() argument must have __dict__ attribute
Want to check how much you know Python?