Python 如何直接调用类方法的引用?

有的时候,需要把 class 的 method 传到其他地方去,然后再调用,但是这样,self 不会被自动填充。

比如下面这样的代码:

from typing import Callable
from loguru import logger


class Work:
    def run(self, data: str):
        logger.debug(data)


method = Work.run


method('哈哈')

报错了:

─➤  python -u "/home/bot/Desktop/ideaboom/011.py"
Traceback (most recent call last):
  File "/home/bot/Desktop/ideaboom/011.py", line 17, in <module>
    method('哈哈')
TypeError: Work.run() missing 1 required positional argument: 'data'

然后我改成了下面这样:

from typing import Callable
from loguru import logger


class Work:
    def run(self, data: str):
        logger.debug(data)


method = Work.run


# method('哈哈')

instance = Work()
method(instance, '哈哈')

跑通了:

─➤  python -u "/home/bot/Desktop/ideaboom/011.py"           
2022-08-02 22:41:15.461 | DEBUG    | __main__:run:7 - 哈哈

可以跑通了,但是感觉这样是不对的,因为 run 的 self 表示的是实例,我实例化了之后,再填充到 run 中,感觉怪怪的。

正确的做法应该是什么呢?

阅读 1.7k
1 个回答

run的self表示的是实例化的对象,而不是该class本身,如果你不希望在使用某类的函数时将其实例化,可以将self参数去除,之后即使是method("哈哈"还是Work.run("哈哈")都可以运行

还有一个挺经典的例子

class x:
    def __init__(self):
        self.run = run

def run(self, ctx):
    print(ctx)
Test=x()
Test.run("Hello")

这段代码将外部函数作为一个类的方法,但是最后运行中会提示缺少参数
你会发现外部函数run中的self参数无法通过实例化x使用Test.run来赋予该参数实例化对象
此时外置函数run在Test.run中的体现是作为类的一个变量,所以会缺少参数。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题