
Python Class - Get dictionary of class instance (dict and vars)
Python class instance has __dict__
method. We can get the dictionary of class instance attributes as follow.
class Employee:
def __init__(self, name, age):
self.name = name
self.age = age
def hello(self):
print("I'm " + self.name + ".")
e = Employee('Bob', 43)
d = e.__dict__
print(d)
# {'name': 'Bob', 'age': 43}
e
is an Employee instance whose name is Bob
and age is 43
. d
is a dictionary of Bob's data (instance attributes).
Employee class has hello
method but it is not contained in the dictionary d
.
Another way to get dictionary
vars
is a Python built-in function that returns instance attributes as dictionary.
class Employee:
def __init__(self, name, age):
self.name = name
self.age = age
def hello(self):
print("I'm " + self.name + ".")
e = Employee('Bob', 43)
d = vars(e)
print(d)
# {'name': 'Bob', 'age': 43}
print(type(d))
# <class 'dict'>
Both can be used in Class inheritance
The next example shows class Book inherits class Product. book
is a Book instance and what does __dict__
returns?
class Product:
def __init__(self, price):
self.price = price
def is_expensive(self):
if 10 < self.price:
print('Expensive')
else:
print('Not Expensive')
class Book(Product):
def __init__(self, price, page):
super().__init__(price)
self.page = page
book = Book(price=24, page=549)
d = book.__dict__
print(d) # {'price': 24, 'page': 549}
v = vars(book)
print(v) # {'price': 24, 'page': 549}
__dict__
and vars
returns the same dictionary.
Class attributes are ignored by vars function
The above code shows vars
returns instance attributes as dictionary but it ignores class attributes.
class Product:
id = 7
def __init__(self, price):
self.price = price
class Book(Product):
def __init__(self, price, page):
super().__init__(price)
self.page = page
book = Book(price=24, page=549)
print(book.id) # 7
print(book.price) # 24
print(book.page) # 549
d = book.__dict__
print(d) # {'price': 24, 'page': 549}
v = vars(book)
print(v) # {'price': 24, 'page': 549}
book
instance has id
attribute and it's 7. But __dict__
and vars
returns only price and page.
vars can return class itself
__dict__
and vars
return Book.
class Product:
id = 7
def __init__(self, price):
self.price = price
class Book(Product):
def __init__(self, price, page):
super().__init__(price)
self.page = page
print(Book.id) # 7
d = Book.__dict__
print(d)
# {'__module__': '__main__', '__init__': <function Book.__init__ at 0x11a239280>, '__doc__': None}
v = vars(Book)
print(v)
# {'__module__': '__main__', '__init__': <function Book.__init__ at 0x11a239280>, '__doc__': None}
id
is a class attribute but __dict__
ignores the attribute.
Comments
Powered by Markdown