Python中callable函数如何使用?
2017-09-04 20:05
816 查看
本文和大家分享的主要是python中使用callable函数相关内容,一起来看看吧,希望对大家学习python有所帮助。
可以通过下面的例子来学习一下什么样的对象是可以调用的:
# File: builtin-callable-example-1.py
def dump(function):
if callable(function):
print(function, "is callable")
else:
print(function, "is *not* callable")
class A:
def method(self, value):
return value
class B(A):
def __call__(self, value):
return value
a = A()
b = B()
dump(0) # simple objects
dump("string")
dump(callable)
dump(dump) # function
dump(A) # classes
dump(B)
dump(B.method)
dump(a) # instances
dump(b)
dump(b.method)
输出结果如下:
== RESTART: D:/work/csdn/python_Game1/example/builtin-callable-example-1.py ==
0 is *not* callable
string is *not* callable
is callable
is callable
is callable
is callable
is callable
<__main__.a object="" at="" 0x0000021fde6f22b0="">is *not* callable
<__main__.b object="" at="" 0x0000021fde6f24a8="">is callable
<bound method A.method of <__main__.b object="" at="" 0x0000021fde6f24a8="">> is callable
>>>
在这里值得注意是A和B对象都是可以调用的,但是A的实例对象不能调用,因为它没有实现__call__方法。
来源:大坡3D软件开发
可以通过下面的例子来学习一下什么样的对象是可以调用的:
# File: builtin-callable-example-1.py
def dump(function):
if callable(function):
print(function, "is callable")
else:
print(function, "is *not* callable")
class A:
def method(self, value):
return value
class B(A):
def __call__(self, value):
return value
a = A()
b = B()
dump(0) # simple objects
dump("string")
dump(callable)
dump(dump) # function
dump(A) # classes
dump(B)
dump(B.method)
dump(a) # instances
dump(b)
dump(b.method)
输出结果如下:
== RESTART: D:/work/csdn/python_Game1/example/builtin-callable-example-1.py ==
0 is *not* callable
string is *not* callable
is callable
is callable
is callable
is callable
is callable
<__main__.a object="" at="" 0x0000021fde6f22b0="">is *not* callable
<__main__.b object="" at="" 0x0000021fde6f24a8="">is callable
<bound method A.method of <__main__.b object="" at="" 0x0000021fde6f24a8="">> is callable
>>>
在这里值得注意是A和B对象都是可以调用的,但是A的实例对象不能调用,因为它没有实现__call__方法。
来源:大坡3D软件开发
相关文章推荐
- Python下如何使用第三方函数库
- Python中如何避免使用多个分支语句(多个if和else)——函数字典(Function Map)简介
- python 9-1 如何使用函数装饰器,定义函数装饰器,用来生成一个原函数基础添加新功能的函数,替代原函数
- python当中的yield函数具体如何使用
- 【python】如何批量读取文件夹的所有文件数据,os模块与open函数结合使用实例
- 学python(03)—— 如何使用函数实现一个随机字符串里的大小写字符互换
- Python2.7 -- 如何使用函数
- python如何使用生成器函数实现可迭代对象
- 如何使用不同参数组合生成独立的TestCase函数(Python)
- 如何使用Python api 函数写股票策略
- Python的enumerate 枚举函数如何使用?
- python 9-2 如何为被装饰的函数保存元数据,使用标准库functools中的装饰器wraps 装饰内部包裹函数
- 如何在C++中使用类似python的字符串split()函数
- python 8-1 如何使用多线程,Thread创建线程,执行函数赋值给target//类+函数放在run方法中执行
- python-7-如何使用生成器函数实现可迭代对象?
- 如何使用SetWindowRgn函数创建异形窗口
- 如何使用SendMessage自定义消息函数(VC实例)
- 如何:使用自定义函数对 ASP.NET 服务器控件进行验证
- 在OpenFOAM中如何解决既使用模板又要调用子类函数的方法
- 如何通过使用 SQL Server 中的 Detach 和 Attach 函数将 SQL Server 数据库移到新位置