In Python, Is type implemented as a callable class?

Viewed 118

when I call type(int), it returns type; when I call type(10), it returns int (and, why is this not the string 'int', but just int?).

type seems to be a class inherited from the universal base class object. So, if it's a class, why I can call type(int)? is the operator '()' reloaded into a class method like C++?

I am quite confused.

1 Answers

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
Related