类方法:function(self)和function的区别在哪里?

问题描述

我有点困惑。

以下两个 python 代码片段都返回相同的值:

首先:

class Test():

    def __init__(self):
        None


    def outer_function(self):
        self.i = "This is the outer function" 

        def inner_function():
            y = "This is the inner function"

            return print(y)

        
        value_from_inner_function = inner_function()
        return print(self.i)

testClass = Test()
testClass.test_function()

第二:

class Test():

    def __init__(self):
        None


    def outer_function(self):
        self.i = "This is the outer function" 

        def inner_function(self):
            self.y = "This is the inner function"

            return print(self.y)

        
        value_from_inner_function = inner_function(self)
        return print(self.i)

testClass = Test()
testClass.test_function()

两个片段都返回。

This is the inner function
This is the outer function

我想知道,应该使用两种情况中的哪一种? 我的假设是,内部函数仅安装供外部类方法使用(在本例中为 outer_function)。

所以不需要实例化,因为外部类方法可以访问它。

因此,我猜第一个片段是“更”正确的片段。是吗?

如果这是真的,片段 1 和片段 2 之间是否存在值得注意的“性能”差异?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)