简体   繁体   English

将类实例变量分配给Python方法中的局部变量

[英]Assign a class instance variable to a local variable within a method in Python

It is possible to assign a class instance variable to a local variable within a method, such as: 可以将类实例变量分配给方法中的局部变量,例如:

class Foo(object):
    def __init__(self):
        self.bar = 'bar'

    def baz(self):
        # assign instance variable to local variable with a method
        bar = self.bar

        # do work with local variable
        bar = "qux"

        # update value of instance variable
        self.bar = bar
        return self

By doing this, one is able to refer to bar instead of self.bar within the scope of Foo.baz() . 这样,就可以在Foo.baz()范围内引用bar而不是self.bar

Is it wrong, or Unpythonic, to do this? 这样做是错误的还是Unpythonic?

Doing that is perfectly fine. 这样做非常好。 You could argue that you don't need to do that (at least in your example, you could reduce the method to two lines if you don't use the local variable), but there isn't really any problem with doing it. 您可能会争辩说您不需要这样做(至少在您的示例中,如果您不使用局部变量,则可以将方法减少到两行),但是这样做确实没有任何问题。

There are certain effects which might end up making one or the other way more preferable: 有某些结果可能最终使一种或另一种方法更可取:

  • Creating a local variable obviously creates another local variable 创建一个局部变量显然会创建另一个局部变量
  • Having a temporary local variable for this requires more code, increasing the overall complexity of the method 为此,拥有一个临时的局部变量需要更多代码,从而增加了方法的整体复杂性
  • Accessing a local variable is faster than accessing an instance attribute 访问局部变量比访问实例属性
  • Having only one point where you update the instance attribute moves the method closer to atomicity (it won't be purely atomic though) and avoids intermediary values on the attribute 仅更新实例属性的一点就使方法更接近原子性(虽然它不是纯粹的原子性),并且避免了属性上的中间值
  • Similarly, if accessing or modifying self.bar has side effects, then doing it only once might be desirable over triggering them multiple times 同样,如果访问或修改self.bar有副作用,那么最好只执行一次,而不是多次触发它们。

All of these effects are usually super minimal and don't matter at all . 所有这些影响通常都是极小的, 根本没关系 Yet they are there, and just maybe they might become relevant to you. 但是它们在那里, 也许它们可能与您息息相关。 Until then, just use what you are most comfortable with. 在此之前,请使用最舒适的东西。

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

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