To clarify, type
is a metaclass, of which classes are instances. Just as an ordinary object is an instance of a class, any class in Python 3, is an instance of the type metaclass.
This means, that type of an object is its corresponding class, but type of a class is its metaclass which is a type object as well.
> type(type)
<class 'type'>
Interestingly, the type of type is type as well. More details here.
As per official documentation -
class type(name, bases, dict)
With one argument, return the type of an object. The return value is a
type object and generally the same object as returned by object.__class__.
So, type class when passed a single argument should return similar results as object.__class__
To test this and understand methods, classes, and metaclasses in python, let's define our own class.
class myclass():
def __init__(self,s):
self.m = s
self.n = s*2
self.o = s*3
Notice that the __init__()
method (which is invoked during instantiation of the class) takes in the parameter which allows the class to be instantiated as an object. Therefore, instantiating a class looks almost exactly the same as calling a method.
obj = myclass('hello world ')
#Returning the self dict
obj.__dict__
{'m': 'hello world ',
'n': 'hello world hello world ',
'o': 'hello world hello world hello world '}
Now let's check the class of the object and the class of the class to which the object belongs (metaclass).
#Class of object obj
> obj.__class__
__main__.myclass
#Class of class of obj = Class of myclass
> obj.__class__.__class__
type
#Class of class of class of obj = Class of type
> obj.__class__.__class__.__class__
type