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 TypeErrorid=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
x = 10
y = "example"
print(vars()) # Output: current local variables
Output:
{'x': 10, 'y': 'example'}
class SimpleClass:
def __init__(self, name):
self.name = name
obj = SimpleClass("test")
print(vars(obj)) # Output: {'name': 'test'}
Output:
{'name': 'test'}
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
class Person:
def __init__(self, name):
self.name = name
p = Person("Alice")
vars(p)['name'] = "Bob"
print(p.name) # Output: Bob
Output:
Bob
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.