Which method can you use to determine whether an object is an instance of a class python?

In this article, we will cover about type() and isinstance() function in Python, and what are the differences between type() and isinstance().

What is type in Python?

Python has a built-in method called type which generally comes in handy while figuring out the type of the variable used in the program in the runtime. The canonical way to check for type in Python is given below:

Syntax of type() function

type(object)
type(name, bases, dict)

Example 1: Example of type() with a Single Object Parameter

In this example, we are trying to check the data type of each variable, such as x, s, and y using type() function.

Python3

x = 5

s = "geeksforgeeks"

y = [1, 2, 3]

print(type(x))

print(type(s))

print(type(y))

Output:

class 'int'
class 'str'
class 'list'

Example 2: Example of type() with a name, bases, and dict Parameter 

If you need to check the type of an object, it is recommended to use the Python isinstance() function instead. It’s because isinstance() function also checks if the given object is an instance of the subclass.

Python3

o1 = type('X', (object,), dict(a='Foo', b=12))

print(type(o1))

print(vars(o1))

class test:

    a = 'Foo'

b = 12

o2 = type('Y', (test,), dict(a='Foo', b=12))

print(type(o2))

print(vars(o2))

Output:

{'b': 12, 'a': 'Foo', '__dict__': , '__doc__': None, '__weakref__': }
{'b': 12, 'a': 'Foo', '__doc__': None}

What is isinstance() in Python?

The isinstance() function checks if the object (first argument) is an instance or subclass of the class info class (second argument).

Syntax of isinstance() function

Syntax: isinstance(object, classinfo) 

Parameter:

  • object : object to be checked
  • classinfo : class, type, or tuple of classes and types

Return: true if the object is an instance or subclass of a class, or any element of the tuple false otherwise. 

If class info is not a type or tuple of types, a TypeError exception is raised.

Example 1: 

In this example, we will see test isinstance() for the class object.

Python3

class Test:

    a = 5

TestInstance = Test()

print(isinstance(TestInstance, Test))

print(isinstance(TestInstance, (list, tuple)))

print(isinstance(TestInstance, (list, tuple, Test)))

Output:

True
False
True

Example 2:

In this example, we will see test isinstance() for the integer, float, and string object.

Python3

weight = isinstance(17.9, float)

print("is a float:", weight)

num = isinstance(71, int)

print("is an integer:", num)

string = isinstance("Geeksforgeeks", str)

print("is a string:", string)

Output:

is a float: True
is an integer: True
is a string: True

Example 3:

In this example, we will see test isinstance() for the tuple, list, dictionary, and set object.

Python3

tuple1 = isinstance(('A', 'B', 'C'),tuple)

print("is a tuple:", tuple1)

set1 = isinstance({'A', 'B', 'C'},set)

print("is a set:", set1)

list1 = isinstance(['A', 'B', 'C'],list)

print("is a list:", list1)

dict1 = isinstance({"A":"1", "B":"2", "C":"3"},dict)

print("is a dict:", dict1)

Output:

is a tuple: True
is a set: True
is a list: True
is a dict: True

What are the differences between type() and isinstance()?

One elementary error people make is using the type() function where isinstance() would be more appropriate.

  • If you’re checking to see if an object has a certain type, you want isinstance() as it checks to see if the object passed in the first argument is of the type of any of the type objects passed in the second argument. Thus, it works as expected with subclassing and old-style classes, all of which have the legacy type object instance.
  • type(), on the other hand, simply returns the type object of an object, and comparing what it returns to another type object will only yield True when you use the exact same type object on both sides. In Python, it’s preferable to use Duck Typing( type checking is deferred to run-time, and is implemented by means of dynamic typing or reflection) rather than inspecting the type of an object. 

Python3

class User(object):

    def __init__(self, firstname):

        self.firstname = firstname

    @property

    def name(self):

        return self.firstname

class Animal(object):

    pass

class Fox(Animal):

    name = "Fox"

class Bear(Animal):

    name = "Bear"

for a in [User("Geeksforgeeks"), Fox(), Bear()]:

    print(a.name)

Output:

Geeksforgeeks
Fox
Bear
  • The next reason not to use type() is the lack of support for inheritance.

Python3

class MyDict(dict):

    def __init__(self):

        self["initial"] = "some data"

d = MyDict()

print(type(d) == dict)

print(type(d) == MyDict)

d = dict()

print(type(d) == dict)

print(type(d) == MyDict)

Output:

False
True
True
False
  • The MyDict class has all the properties of a dict, without any new methods. It will behave exactly like a dictionary. But type() will not return the expected result. Using isinstance() is preferable in this case because it will give the expected result: 

Python3

class MyDict(dict):

    def __init__(self):

        self["initial"] = "some data"

d = MyDict()

print(isinstance(d, MyDict))

print(isinstance(d, dict))

d = dict()

print(isinstance(d, MyDict))

print(isinstance(d, dict))

Output:

True
True
False
True

Which method is used to determine whether an object is an instance of a class?

The java “instanceof” operator is used to test whether the object is an instance of the specified type (class or subclass or interface). It is also known as type comparison operator because it compares the instance with type. It returns either true or false.

Which methods of Python are used to determine the type of instance and inheritance?

Python has two built-in functions that work with inheritance:.
Use isinstance() to check an instance's type: isinstance(obj, int) will be True only if obj.__class__ is int or some class derived from int ..
Use issubclass() to check class inheritance: issubclass(bool, int) is True since bool is a subclass of int ..

What is instance of class in Python?

Instance is an object that belongs to a class. For instance, list is a class in Python. When we create a list, we have an instance of the list class. In this article, I will focus on class and instance variables. I assume you have a basic knowledge about classes in Python.

What is an object an object is an instance of a class?

an object is an element (or instance) of a class; objects have the behaviors of their class. The object is the actual component of programs, while the class specifies how instances are created and how they behave. method: a method is an action which an object is able to perform.