Movatterモバイル変換


[0]ホーム

URL:


Python Tutorial

Python type() Function



ThePython type() function is abuilt-in function that returns the type of specified object and is commonly used for debugging purposes. The two main use cases of thetype() function are as follows −

  • When we pass a single argument to this function, it returns the type of the given object.

  • When three arguments are passed, it allows for the dynamic creation of a new type object.

Syntax

Following is the syntax of the Pythontype() function −

type(object, bases, dict)# ortype(object)

Parameters

The Pythontype() function accepts two parameters −

  • object − It represents an object such as alist,string, or any other iterable.

  • bases − It is an optional parameter that specifies a base class.

  • dict − It is also an optional parameter. It represents a dictionary that stores the namespace.

Return Value

The Pythontype() function returns the type of a given object. If we pass three arguments, it will return a new type object.

type() Function Examples

Practice the following examples to understand the use oftype() function in Python:

Example: Use of type() Function

The following example shows the basic usage of Pythontype() function. In the code below, we are displaying the classes for the most useddata types.

var1 = 5var2 = 5.2var3 = 'hello'var4 = [1,4,7]var5 = {'Day1':'Sun','Day2':"Mon",'Day3':'Tue'}var6 = ('Sky','Blue','Vast')print(type(var1))print(type(var2))print(type(var3))print(type(var4))print(type(var5))print(type(var6))

Following is an output of the above code −

<class 'int'><class 'float'><class 'str'><class 'list'><class 'dict'><class 'tuple'>

Example: Getting Type of Classes Using type() Function

The class named "type" is a superclass, from which all other classes are derived. The type object is also an instance of this class. Therefore, applying type() function to the Python classes will return "class type" as a result.

print("Displaying the type of Python classes:")print("Type of int class is", type(int))print("Type of dict class is", type(dict))print("Type of list class is", type(list))print("Type of type class is", type(type))

Output of the above code is as follows −

Displaying the type of Python classes:Type of int class is <class 'type'>Type of dict class is <class 'type'>Type of list class is <class 'type'>Type of type class is <class 'type'>

Example: Creating New Type Object Using type() Function

If we pass three arguments to thetype() function, it will create a new type object. In the code below, we have created "Tutorialspoint" as a main class, an object as a base and adictionary with two keys and values.

Object = type("Tutorialspoint", (object, ), dict(loc="Hyderabad", rank=1))print(type(Object))print(Object)

Following is the output of the above Python code −

<class 'type'><class '__main__.Tutorialspoint'>
python_built_in_functions.htm
Print Page
Advertisements

[8]ページ先頭

©2009-2025 Movatter.jp