Skip to content Skip to sidebar Skip to footer

The Built-in Keyword Type Means A Function Or A Class In Python?

In most posts, people often say type is a built-in function if it is provided with one argument, and it is a metaclass if provided with 3 arguments. But in python's doc, the signat

Solution 1:

The distinction between classes and functions in Python is not as stark as in other languages.

You can use function call syntax to invoke an actual function, but also an instance of a class with the __call__ method, and even a class that overrides __new__ can behave like a function.

The word Python uses for all these is callable: an object you can invoke using the call syntax (foo()), which evaluates to a result.

The type built-in is a callable. It can be called.

Sometimes you treat type like a function, and it works, so you can say it's a function. Other times you treat it like a class, so you can say it's a class. The actual implementation should not matter.

This is duck typing in action: if it walks like a duck, and it quacks like a duck, then it must be a duck.

Solution 2:

The built-in type always returns a type object, which is basically a class. That's true whether it's the one-argument form or the three-argument form. In the one-argument case, the returned object is the type (class) of the argument. In the three argument case, the returned object is a new type object (class). In both cases the returned object can be used to instantiate new objects (instances of the class).

Some classes can be used as metaclasses. That's a common use case for the three-argument form of type. But there are other ways to make a class that can be used as a metaclass, and other uses for the three-argument form of type.

It's not that much different from int, which is a built-in function that returns an object of type int. int is also the name of a class, and can be used to create new objects:

>>>x = int()>>>x
0
>>>type(x)
<class 'int'>

And also like type, it has more than one form:

>>>y = int("A", 16)>>>y
10

Post a Comment for "The Built-in Keyword Type Means A Function Or A Class In Python?"