理解callable和使用partial函数

callable() 函数

callable()函数 用于检查一个对象是否是可调用的,如果返回 True,object 仍然可能调用失败;但如果返回 False,调用对象 object 绝对不会成功。

对于函数、方法、lambda 函式、 类以及实现了 call 方法的类实例, 它都返回 True。

callable(object) 函数签名 object 对象

print(callable(0))  # False
print(callable("tom"))  # False
print("=" * 50)


def add(a, b):
    return a + b


print(callable(add))  # True
print("=" * 50)


class A:
    def method(self):
        return 0


print(callable(A))  # True
print(callable(A()))  # False
print("=" * 50)


class B:
    def __call__(self, *args, **kwargs):
        return 0


print(callable(B))  # True
print(callable(B()))  # True
print("=" * 50)
print("#"*100)

from functools import partial的使用

import math


def spam(a, b, c, d):
    print(a, b, c, d)


def distance(p1, p2):
    x1, y1 = p1
    x2, y2 = p2
    return math.hypot(x2 - x1, y2 - y1)


def output_result(result, log=None):
    if log is not None:
        log.debug("'Got:%r", result)


def add(a, b):
    return a + b


if __name__ == '__main__':
    from functools import partial
    # s1 = partial(spam, 1)
    # s1(2, 3, 4)  # 1,2,3,4
    # s1(4, 5, 6)
    # s2 = partial(spam, 1, 2, d=200)  # partial 返回新的callable 对象
    # s2(3)
    # points = [(1, 2), (3, 4), (5, 6), (7, 8)]
    # pt = (100, 200)
    # points.sort(key=partial(distance, pt))
    # print(points)
    import logging
    from multiprocessing import Pool

    logging.basicConfig(level=logging.DEBUG)
    log = logging.getLogger("test")
    p = Pool()
    p.apply_async(add, (3, 4), callback=partial(output_result, log=log))
    p.close()
    p.join()

猜你喜欢

转载自www.cnblogs.com/action-go/p/11956783.html