类方法: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 之间是否存在值得注意的“性能”差异?

解决方法

在第一个版本中,-- from the Data.Functor.Contravariant source newtype Op a b = Op { getOp :: b -> a } instance Contravariant (Op a) where contramap f g = Op (getOp g . f) y 的局部变量。当函数返回时它就会消失。

在第二个版本中。 inner_function() 是对象的一个​​属性。分配它会对对象进行永久更改,因此您可以在内部函数返回后引用它。例如

self.y