Python中callable函数如何使用?

来源:互联网 发布:淘宝换购拍下 编辑:程序博客网 时间:2024/06/01 09:57
本文和大家分享的主要是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
  >>>
  在这里值得注意是AB对象都是可以调用的,但是A的实例对象不能调用,因为它没有实现__call__方法。
来源:大坡3D软件开发