Python built-in Method - type()

w‮tfigi.ww‬idea.com

The type() method is a built-in function in Python that returns the type of an object. It takes a single parameter, which is the object whose type is to be determined.

Here is the syntax for the type() method:

type(object)

The object parameter can be any object in Python, including built-in types like integers, floats, and strings, as well as custom-defined classes and objects.

Here are some examples of using the type() method:

x = 5
print(type(x))    # output: <class 'int'>

y = "hello"
print(type(y))    # output: <class 'str'>

class MyClass:
    pass

z = MyClass()
print(type(z))    # output: <class '__main__.MyClass'>

In the first example, we create an integer variable x with the value 5, and then use the type() method to determine its type, which is int. In the second example, we create a string variable y with the value "hello", and then use the type() method to determine its type, which is str. In the third example, we define a custom class MyClass and then create an instance of it using the MyClass() constructor. We then use the type() method to determine the type of the instance, which is __main__.MyClass, where __main__ is the name of the module in which MyClass is defined.

The type() method is useful when you need to determine the type of an object, especially in cases where you are working with custom classes and objects. By knowing the type of an object, you can then access its methods and attributes, or perform operations on it based on its specific type.