如何解决类方法: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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。