vars()

vars() returns the __dict__ attribute of the given object.

class Animal():
    #instance attributes
    def __init__(self1,name1,age):
        self1.name= name1
        self1.age=age

#instantiate the Animal  class
tiger=Animal("Ronald",5)  # tiger is an object of Animal class

print(vars(tiger)) # {'name': 'Ronald', 'age': 5}
Output
{'name': 'Ronald', 'age': 5}
if the object doesn't have __dict__ attribute then it will return TypeError
id=5
print(vars(id))
Output
TypeError                Traceback (most recent call last)
 in 
      1 id=5
----> 2 print(vars(id))

TypeError: vars() argument must have __dict__ attribute

Example 1: Using vars() Without Arguments

x = 10
y = "example"
print(vars())  # Output: current local variables
Output:
{'x': 10, 'y': 'example'}

Example 2: Using vars() on a Custom Class

class SimpleClass:
    def __init__(self, name):
        self.name = name
obj = SimpleClass("test")
print(vars(obj))  # Output: {'name': 'test'}
Output:
{'name': 'test'}

Example 3: Using vars() on Built-in Types

my_list = [1, 2, 3]
try:
    print(vars(my_list))
except TypeError as e:
    print(f"Error: {e}")
Output:
Error: vars() argument must have __dict__ attribute

Example 4: Modifying Object Attributes with vars()

class Person:
    def __init__(self, name):
        self.name = name

p = Person("Alice")
vars(p)['name'] = "Bob"
print(p.name)  # Output: Bob
Output:
Bob

All Built in Functions in Python Class Object & Methods

Subhendu Mohapatra — author at plus2net
Subhendu Mohapatra

Author

🎥 Join me live on YouTube

Passionate about coding and teaching, I publish practical tutorials on PHP, Python, JavaScript, SQL, and web development. My goal is to make learning simple, engaging, and project‑oriented with real examples and source code.



Subscribe to our YouTube Channel here



plus2net.com







Python Video Tutorials
Python SQLite Video Tutorials
Python MySQL Video Tutorials
Python Tkinter Video Tutorials
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
©2000-2025   plus2net.com   All rights reserved worldwide Privacy Policy Disclaimer