您的位置:首页 > 编程语言 > Python开发

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软件开发
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐