【Python】将方法传递给函数的参数,并在函数中使用该方法

方法

    def sum(x, y):
        return x+y

 

函数

class demo:

    def __init__(self, x, y):
        self.x = x
        self.y = y

    def run(self, func):
        r = func(self.x, self.y)
        logs.debug(r)

 

调用

if __name__ == "__main__":
    demo(10, 20).run(sum)
    demo(1024, 2048).run(sum)
    demo(123.54, 321.28).run(sum)

 

执行结果

 

 

 

 完整实例

# coding:utf-8
from loguru import logger as logs

class demo:

    def __init__(self, x, y):
        self.x = x
        self.y = y

    def run(self, func):
        r = func(self.x, self.y)
        logs.debug(r)

class count:
    @staticmethod
    def sum(x, y):
        return x + y

    @staticmethod
    def sub(x, y):
        return x - y

    @staticmethod
    def mul(x, y):
        return x * y

    @staticmethod
    def division(x, y):
        return x / y


if __name__ == "__main__":
    c = count()
    logs.info(c.sum(10, 20))   # 正常调用
    demo(10, 20).run(c.sum) # 传参
    demo(1024, 2048).run(c.sub)
    demo(10, 100).run(c.mul)
    demo(999, 9).run(c.division)

 

 执行结果

 

posted @ 2022-11-09 16:42  Phoenixy  阅读(103)  评论(0)    收藏  举报