type and isinstance in Python program

PythonServer Side ProgrammingProgramming

In this tutorial, we are going to learn about the type and isinstance built-in functions of Python. These functions are used to determine the type of an object in general. Let's see them one by one.

type(object)

type is used to know the type of an object. For example, if we have an object val with value 5. The type of that object is int. We can get that using the type function. Let's follow the general procedure to achieve the result.

  • Initialize the object.
  • Get the type of the object using type(object) function.
  • Display the type.

Below is one example which explains the type(object) function.

Example

# initialzing an object
val = 5
# getting type of the object
object_type = type(val)
# displaying the type
print(object_type)

Output

If you run the above program, you will get the following results.

<class 'int'>

isinstance(object, class)

isinstance(object, class) takes two arguments first one is an object and the second one is class. It returns True if the object is subclass the given class or else it returns False. For example, if we take an object nums with values {1, 2, 3} then, passing it and class set to isintance will return True. Follow the below steps to examine it.

  • Initialize the object.
  • Invoke the isinstance(object, class) with the object and the class.

Let's see one example.

Example

# initializing the object
nums = {1, 2, 3}
# invoking the isinstance(object, class) function
print(isinstance(nums, set))

Output

If you run the above program, you will get the following results.

True

So, isinstance function checks for subclass as well for type. If it returns True, then the object is of a kind given the class. We can also use it for custom classes as well. Let's see one example.

Example

# wrinting a class
class SampleClass:
   # constructor
   def __init__(self):
      self.sample = 5
# creating an instance of the class SampleClass
sample_class = SampleClass()
# accessing the sample class variable
print(sample_class.sample)
# invoking the isinstance(object, class) function
print(isinstance(sample_class, SampleClass))

Output

If you run the above program, you will get the following results.

5
True

Conclusion

Use the functions based on your needs. Both are handy to use for the detection of the type of an object. If you are having any trouble following the tutorial, mention it in the comment section.

raja
Published on 01-Nov-2019 07:49:32
Advertisements