简体   繁体   English

自变量与传递给def的python存储

[英]python store in self variable vs. passing to def

How should I pass a variable in between methods in a class? 我应该如何在类中的方法之间传递变量? Like this, as an argument: 像这样,作为一个论点:

class Yadayada:
    def foo(self):
        for i in somelist:
            pass_var = i * blah blah blah
            output = self.bar(pass_var)

    def bar(self,pass_var):
        a= pass_var * whatever
        return a

or like this, store it in a variable? 或者像这样,将它存储在一个变量中?

class Yadayada:
    def foo(self):
        for i in somelist:
            self.pass_var = i * blah blah blah
            output = self.bar()

    def bar(self):
        a= self.pass_var * whatever
        return a

What's the best way and why? 什么是最好的方式和原因? Or does it even matter? 或者甚至重要吗? Note: I will not be using the variable pass_var in the rest of the code. 注意:我不会在其余代码中使用变量pass_var。

This is a design decision. 这是一个设计决定。 Passing it as a parameter will keep that passed value around for the life of that function. 将它作为参数传递将在该函数的生命周期中保持该值传递。 Storing it as an attribute on the object will keep it around for the life of the instance - that is likely to be much longer. 将它作为属性存储在对象上将在实例的生命周期中保留它 - 这可能会更长。

The question you should ask yourself is does this value help describe the instance or is it something the instance owns? 你应该问自己的问题是这个值有助于描述实例,还是实例拥有的东西? - if either of these things are true, then store it. - 如果其中任何一个都是真的,那么存储它。

If it's just something used to compute a value (which is what it sounds like) then there is no reason to store it. 如果它只是用于计算值的东西(听起来就是这样),那么就没有理由存储它。 Storing it implies you want to use it later. 存储它意味着您希望以后使用它。

If you are unsure, err on the side of passing the value to the function. 如果您不确定,请将值传递给函数。 This reduces the chance for error (calling the function when the value isn't set on the class), and it reduces the amount of memory being used. 这样可以减少出错的可能性(在类没有设置值时调用函数),并减少了使用的内存量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM