
Python type and isinstance - Get the type of an object and check if the object is list
type
is a Python built-in function that returns type of object.
a = 1
b = 'Microsoft'
c = [3, 4]
d = {'book': 27, 'pen': 91}
e = (4, 5, 6, 7)
f = {'mac', 'book'}
print(type(a)) # <class 'int'>
print(type(b)) # <class 'str'>
print(type(c)) # <class 'list'>
print(type(d)) # <class 'dict'>
print(type(e)) # <class 'tuple'>
print(type(f)) # <class 'set'>
type
is a special reserved word in Python so functions or variables should not be named type
.
Type
s = 'a'
if type(s) == str:
print('a is str')
else:
print('a is not str')
# a is str
s
is a string so type(s) == str
is true. The right value is str
, not 'str'
. So it's meaningless to compare type(s) and 'str'
.
s = 'a'
if type(s) == 'str':
print('a is str')
else:
print('a is not str')
# a is not str
Isinstance
isinstance
is a function to check the object type.
a = [3, 4]
if isinstance(a, list):
print('a is list.')
else:
print('a is not list.')
# a is list.
The first argument is an object, and the second is a class itself. isinstance(a, list)
returns True if a
is a list or False if a
is not a list.
Another example:
a = [3, 4]
if isinstance(a, tuple):
print('a is tuple.')
else:
print('a is not tuple.')
# a is not tuple.
Class inheritance
class Product:
def __init__(self, price):
self.price = price
class Book(Product):
def __init__(self, price, page):
super().__init__(price)
self.page = page
b = Book(price=12, page=80)
if type(b) == Product:
print('b is a product')
else:
print('b is not a product')
# b is not a product
if type(b) == Book:
print('b is a book')
else:
print('b is not a book')
# b is a book
b
is the Book object and Book inherits Product. type(b)
simply returns Book
so you can't get what the object inherits from by using type
. But isinstance
gets all the inheritance of an object.
class Product:
def __init__(self, price):
self.price = price
class Book(Product):
def __init__(self, price, page):
super().__init__(price)
self.page = page
b = Book(price=12, page=80)
if isinstance(b, Product):
print('b is a product')
else:
print('b is not a product')
# b is a product
if isinstance(b, Book):
print('b is a book')
else:
print('b is not a book')
# b is a book
Because b
is a Book, and therefore, a Product. isinstance(b, Product)
returns True.
Comments
Powered by Markdown