Python Type Object

PythonServer Side ProgrammingProgramming

Everything in Python is an object including classes. All classes are instances of a class called "type".The type object is also an instance of type class. You can inspect the inheritance hierarchy of class by examining the __bases__ attribute of a class object. type() method returns class type of the argument(object) passed as parameter.If single argument type(obj) is passed to type method, it returns the type of given object. If three arguments type(name, bases, dict) is passed, it returns a new type object.

Using type()

Let’s look at the classes for the most used data types. In the below program we initialize some variables and then use the type() to ascertain their class.

Example

 Live Demo

# Some variables
a = 5
b = 5.2
c = 'hello'
A = [1,4,7]
B = {'k1':'Sun','K2':"Mon",'K3':'Tue'}
C = ('Sky','Blue','Vast')
print(type(a))
print(type(b))
print(type(c))

print(type(A))
print(type(B))
print(type(C))

Output

Running the above code gives us the following result −

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

Type of the classes

If we go deeper to look at the type of classes above, we will see that they are all belong to class named ‘type’.

Example

 Live Demo

print(type(int))
print(type(dict))
print(type(list))

print(type(type))

Output

Running the above code gives us the following result −

<class 'type'>
<class 'type'>
<class 'type'>
<class 'type'>

Creating a new Object Type

We can also use a similar approach as above to create new objects. Here we pass three parameters to create the new type object.

Example

 Live Demo

Object1 = type('A', (object,), dict(a='Hello', b=5))
print(type(Object1))
print(vars(Object1))
class NewCalss:
   a = 'Good day!'
   b = 7
Object2 = type('B', (NewCalss,), dict(a='Hello', b=5))
print(type(Object2))
print(vars(Object2))

Output

Running the above code gives us the following result −

<class 'type'>
{'a': 'Hello', 'b': 5, '__module__': '__main__', '__dict__': <attribute '__dict__' of 'A' objects>, '__weakref__': <attribute '__weakref__' of 'A' objects>, '__doc__': None}
<class 'type'>
{'a': 'Hello', 'b': 5, '__module__': '__main__', '__doc__': None}
raja
Published on 25-Jan-2021 07:44:10
Advertisements