Python判断对象是否是function的三种方法

                       

在Python中,判断一个对象是否是方法有如下三种方法。

1. 根据“__call__”属性判断

有时候用python就有这么一种感悟,各种钩子函数就是通过内置的“__”属性实现,python学得好不好,就是对“__”属性理解得透彻不透彻。

python函数在调用时,一定会首先调用其相关“__call__”函数(没有空格),请参见python总结(四):类装饰器与方法的动态添加中的用法。

add = lambda a, b: a + b#   判断成功if(hasattr(add, '__call__')):        print add(1,2)
   
   
  • 1
  • 2
  • 3
  • 4

2. 利用callable判断

这是一个据传快要废弃的方法,但是在Python 2中依旧很好用,如下:

#   判断成功if(callable(add)):        print add(2, 2)
   
   
  • 1
  • 2
  • 3

3. 利用isfunction进行判断

Python的inspect模块包含了大量的与反射、元数据相关的工具函数,isfunction就是其中一种,使用方法如下:

from inspect import isfunction#   判断成功if(isfunction(add)):    print add(5, 5)
   
   
  • 1
  • 2
  • 3
  • 4

4. 无效的types.MethodType

出人意料的是types.MethodType竟然无效(版本2.7.14),如下:

import types#   竟然无效if(isinstance(add, types.MethodType)):    print add.__name__
   
   
  • 1
  • 2
  • 3
  • 4

在这个引申过程中,还发现了一些有意思的现象,不同的function的输出结果不一样:

>>> type(format)<type 'builtin_function_or_method'>>>> type(add)<type 'function'>
   
   
  • 1
  • 2
  • 3
  • 4

更有意思的是,type竟然无法对print进行操作,如下:

>>> type(print)  File "<stdin>", line 1    type(print)             ^SyntaxError: invalid syntax
   
   
  • 1
  • 2
  • 3
  • 4
  • 5

那print是什么?

结论

如何判断一个对象是否是方法,本文提供了3种方法,并发现了一些有意思的现象,再问一遍,print是什么?

           

猜你喜欢

转载自blog.csdn.net/qq_44884577/article/details/89229985