Python - Is it okay to pass self to an external function

☆樱花仙子☆ 提交于 2019-12-20 10:18:12

问题


I have a class, A, which is inherited by a bunch of other classes. Some of these have a few functions which are similar and it would be nice to have those functions defined somewhere else and called by the classes that need them. But those functions call functions defined in the super class.

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)

So I have created my helper functions which take the self object as an argument and I can call the imp_func from inside the helper functions.

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)

This solves the problem.

But should I be doing this? Is this Pythonic?


回答1:


There is no problem with that whatsoever - self is an object like any other and may be used in any context where object of its type/behavior would be welcome.

In Python, as exemplified by the standard library, instances of self get passed to functions (and also to methods, and even operators) all the time.



来源:https://stackoverflow.com/questions/16084623/python-is-it-okay-to-pass-self-to-an-external-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!