Python - 将self传递给外部函数是否可以

els*_*sar 35 python self

我有一个类A,它由一堆其他类继承.其中一些函数有一些相似的函数,将这些函数定义在其他地方并由需要它们的类调用会很好.但是这些函数调用超类中定义的函数.

class A():
    def imp_func(*args):
        # called by the child class functions

Class B(A):
    def common_func(self):
        # some stuff
        self.imp_func(*args)
Run Code Online (Sandbox Code Playgroud)

所以我创建了我的辅助函数,它将self object参数作为参数,我可以imp_func在辅助函数中调用from.

def helper_func(obj, some_args):
    # some common stuff
    obj.imp_func(*args)

class B(A):
    def common_func(self):
        # unique stuff
        helper_func(self, some_args)
Run Code Online (Sandbox Code Playgroud)

这解决了这个问题.

但我应该这样做吗?这是Pythonic吗?

use*_*342 43

没有任何问题 - self是一个像任何其他对象一样的对象,并且可以在欢迎其类型/行为的对象的任何上下文中使用.

在Python,标准库为例证,实例self 得到 传递 函数( 方法, 甚至 运营商)所有 时间.

  • +50,用于非常酷的隐藏超链接中的多个示例。 (2认同)