Python Type

Filed Under: Python

In this tutorial we are going to learn about Python Type. In our previous tutorial we learned about Python String to int, Int to String Conversion.

Python type

Basically, Python has type() function that is used to get the type of an object. If you read our previous tutorial, you might be familiar with Python Type function. The basic structure of python type is given below:

python type syntax

Here, Object is the instance of any class.

The type() function returns a type object. The following basic example will give you idea about python type.

class ClassTest:
    # declare a integer type variable
    var_int = 12

    # declare a string type variable
    var_str = 'monday'

    # declare a tuple type variable
    var_tup = (1, 2, 'mono')

# it will show the ClassTest as a 'type'
print('Type of ClassTest :', type(ClassTest))

ct = ClassTest

# it will show the ClassTest as a 'class'
print('Type of ct :', type(ct))

# it will print the type of var_int as 'int'
print('Type of var_int :', type(ct.var_int))

# it will print the type of var_str as 'str'
print('Type of var_str :', type(ct.var_str))

# it will print the type of var_tup as 'tuple'
print('Type of var_tup :', type(ct.var_tup))

So, the output of the above code will be

Type of ClassTest : <class 'type'>
Type of ct : <class 'type'>
Type of var_int : <class 'int'>
Type of var_str : <class 'str'>
Type of var_tup : <class 'tuple'>

Notice that we can check type of any type of variable or class instance. Also if we define “ct” as below:

ct = ClassTest()
print('Type of ct :', type(ct))

Then it will print output as below since it’s an instance of ClassTest class now.

Type of ct : <class '__main__.ClassTest'>

Why do we need Python type function

Basically Python type is used for testing purpose. You might need to check the type of some variable. At that time you can get that by using python type function. As we know that we can store different type of objects in python array or list in python, so it’s a useful function if we want to process only specific type of elements.

If you are following our tutorials from the beginning, you may notice that in many cases we used python type to make the thing easier to understand.

So, that’s all for python type function.

Leave a Reply

Your email address will not be published. Required fields are marked *

Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages