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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16084623/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 21:44:26  来源:igfitidea点击:

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

pythonself

提问by elssar

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.

我有一个类 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)

So I have created my helper functions which take the self objectas an argument and I can call the imp_funcfrom inside the helper functions.

所以我创建了我的辅助函数,它将 theself object作为参数,我可以imp_func从辅助函数内部调用 the 。

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?

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

采纳答案by user4815162342

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

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

In Python, as exemplified by the standard library, instances of selfgetpassedtofunctions(andalsotomethods, andevenoperators) allthetime.

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