Is a function a class object in python?

I read that a function is a class object in python. To understand, I did the following:

>>> a=10
>>> a.__class__
<type 'int'>
>>> int.__class__
<type 'type'>
>>>
>>>
>>> def T1():
...     print 'test'
...
>>> T1.__class__
<type 'function'>
>>> function.__class__
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'function' is not defined

Q: why does the interpreter throw an error in the second case, and not in the first case? I expected him to return <type 'type'>. Please correct my understanding.

+4
source share
2 answers

This is true, but there is no built-in name for it. You can find another link in the module types:

>>> import types
>>> def T1():
...     print 'test'
...     
>>> T1.__class__ is types.FunctionType
True
>>> print repr(types.FunctionType)
<type 'function'>

So, the only thing you notice is that functionis not a built-in name, as opposed to the names, such as int, type.

+2
source

. , ( ) ( ):

>>> class MyMeta(type): # <-- a custom metaclass, similar to function
        pass

>>> print(MyMeta.__name__)
MyMeta
>>> print(__class__)
<class 'type'>

>>> class MyClass(metaclass = MyMeta):
        pass
>>> print(MyClass.__class__)
<class 'MyMeta'>

MyMeta:

>>> del MyMeta

metaclass, MyMeta, MyMeta ? :

>>> print(MyClass.__class__)
<class 'MyMeta'>

, metaclass MyClass dict.

MyMeta , :

>>> class MyClassTwo(metaclass = MyMeta):
        pass
NameError!!
>>> print(MyMeta.__name__)
NameError!!
>>> print(MyMeta)
NameError!!

: , .

object :

>>> class MyClassTwo(metaclass = MyClass.__class__):
        pass

function ( , , , , ) - function Python. . :

>>> def f(): pass
>>> f.__class__.__class__
<class 'type'>

, function <class 'type'> ( ):

>>> function  = f.__class__
>>> print(function)
<class 'function'>
>>> print(function.__class__)
<class 'type'>
0

Source: https://habr.com/ru/post/1668291/


All Articles