平方X

 找回密码
 立即注册
搜索
热搜: 活动 交友 discuz
查看: 3646|回复: 0

[2539]Python 判断变量是否是一个方法

[复制链接]

414

主题

709

帖子

3656

积分

管理员

Rank: 9Rank: 9Rank: 9

积分
3656
QQ
发表于 2018-6-6 11:28:40 | 显示全部楼层 |阅读模式
[md]
[蚁方阵《Python判断对象是否是function的三种方法》](https://blog.csdn.net/yiifaa/article/details/78046331)

[How do I detect whether a Python variable is a function?](https://stackoverflow.com/questions/624926)

最后选择 callable
# callable
> If this is for Python 2.x or for Python 3.2+, you can also use callable(). It used to be deprecated, but is now undeprecated, so you can use it again. You can read the discussion here: http://bugs.python.org/issue10518. You can do this with:

    callable(obj)
# hasattr
If this is for Python 3.x but before 3.2, check if the object has a __call__ attribute. You can do this with:

    hasattr(obj, '__call__')
# FunctionTypes
The oft-suggested types.FunctionTypes approach is not correct because it fails to cover many cases that you would presumably want it to pass, like with builtins:

    >>> isinstance(open, types.FunctionType)
    False

    >>> callable(open)
    True
   
# isfunction
    >>> from inspect import isfunction
    >>> def f(): pass
    >>> isfunction(f)
    True
    >>> isfunction(lambda x: x)
    True[/md]
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|小黑屋|手机版|Archiver|平方X ( 冀ICP备14018164号 )

GMT+8, 2024-11-21 21:18 , Processed in 0.270255 second(s), 21 queries .

技术支持:Powered by Discuz!X3.4  © 2001-2013 Comsenz Inc.

版权所有:Copyright © 2014-2018 平方X www.pingfangx.com All rights reserved.

快速回复 返回顶部 返回列表