在阅读有关
unification of types的内容时,我偶然发现内置类型有method_descriptors和builtin_function_or_methods而不是方法和函数,为什么呢?
>>> list.append <method 'append' of 'list' objects> >>> type(list.append) <class 'method_descriptor'> >>> [].append <built-in method append of list object at 0x7f0c4214aef0> >>> type([].append) <class 'builtin_function_or_method'> >>> class A(list): ... def append(self): pass ... >>> A.append <function A.append at 0x7f0c42168dd0> >>> type(A.append) <class 'function'> >>> A().append <bound method A.append of []> >>> type(A().append) <class 'method'>
A类到子类列表没有充分的理由,我只是想表明类型不同.
解决方法
区别在于内置输入是C编译的代码描述符,而用户定义的函数代表它的代码
descriptors.有关详细信息,请参阅
source.
此外,虽然内置函数及其方法是静态分配的数据结构,但用户定义的数据结构的内存是以动态方式分配的.甚至大小也不同:描述符的大小在内置函数之间以及类似的用户定义中是相等的,参考C源(上面的链接):
>>> sys.getsizeof(list.append) 72 # built-in >>> sys.getsizeof(dir) 72 # built-in >>> sys.getsizeof(A.__init__) 80 # class/instance method >>> sys.getsizeof(lambda x: x) 120 # static function
所以这些东西看起来不同,居住在不同的地方,表现不同.没有必要给他们相同的名字.
我想为classmethod
添加错过的编译模拟,classmethod_descriptor,
>>> type(float.__dict__['fromhex']) <type 'classmethod_descriptor'>
以及其他一些有趣的类型:
>>> type(A.__init__) <type 'wrapper_descriptor'> >>> type(A.__dict__['__dict__']) <type 'getset_descriptor'>
看到:
> What is a wrapper_descriptor,and why is Foo.__init__
one in this case
> What is the __dict__.__dict__
attribute of a Python class?