partial 函数之参数传入

zj@zj-virtual-machine:/tmp$ cat callback.py
#!/usr/bin/env python
# coding=utf-8
from functools import partial
class D(object):
    def __init__(self, num):
        self._num = num

    def add_callback(self, callback):
        self._callback = callback

    def _run_callback(self):
        print("D _run_callback exec")
        self._callback(self._num)

def f1(a, _):
    print('a :  %s'%a)
    print('_ : %s'%_)

d = D(10)
d.add_callback(partial(f1, 99))  #a = 99, _=self._num
d._run_callback()
zj@zj-virtual-machine:/tmp$ python3 -i callback.py
D _run_callback exec
a :  99
_ : 10
>>> f1
<function f1 at 0x7fa7da78de18>
>>> eg = partial(f1, 109)
>>> eg
functools.partial(<function f1 at 0x7fa7da78de18>, 109)
>>> eg
functools.partial(<function f1 at 0x7fa7da78de18>, 109)
>>> eg(233)
a :  109
_ : 233

Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐