python3callable使用_python --- Python中的callable 函数

转自: http://archive.cnblogs.com/a/1798319/

Python中的callable 函数

callable 函数, 可以检查一个对象是否是可调用的 (无论是直接调用或是通过 apply). 对于函数, 方法, lambda 函式, 类, 以及实现了 _ _call_ _ 方法的类实例, 它都返回 True.

def dump(function):if callable(function):print function, “is callable”else:print function, “is *not* callable”class A:def method(self, value):return valueclass B(A):def _ _call_ _(self, value):return valuea = A()b = B()dump(0) # simple objectsdump(”string”)dump(callable)dump(dump) # functiondump(A) # classesdump(B)dump(B.method)dump(a) # instancesdump(b)dump(b.method)0 is *not* callablestring is *not* callable is callable is callableA is callableB is callable is callable is *not* callable is callable is callable注意类对象 (A 和 B) 都是可调用的; 如果调用它们, 就产生新的对象(类实例). 但是 A 类的实例不可调用, 因为它的类没有实现 _ _call_ _ 方法.你可以在 operator 模块中找到检查对象是否为某一内建类型(数字, 序列, 或者字典等) 的函数. 但是, 因为创建一个类很简单(比如实现基本序列方法的类), 所以对这些 类型使用显式的类型判断并不是好主意.在处理类和实例的时候会复杂些. Python 不会把类作为本质上的类型对待; 相反地, 所有的类都属于一个特殊的类类型(special class type), 所有的类实例属于一个特殊的实例类型(special instance type).这意味着你不能使用 type 函数来测试一个实例是否属于一个给定的类; 所有的实例都是同样 的类型! 为了解决这个问题, 你可以使用 isinstance 函数,它会检查一个对象是 不是给定类(或其子类)的实例. Example 1-15 展示了 isinstance 函数的使用.

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)

0 is *not* callable

string is *not* callable

is callable

is callable

A is callable

B is callable

is callable

is *not* callable

is callable

is callable

注意类对象 (A 和 B) 都是可调用的; 如果调用它们, 就产生新的对象(类实例). 但是 A 类的实例不可调用, 因为它的类没有实现 _ _call_ _ 方法.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值