将类实例变量分配给 Python 方法中的局部变量 [英] Assign a class instance variable to a local variable within a method in Python

查看:61
本文介绍了将类实例变量分配给 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

通过这样做,可以在Foo.baz() 的范围内引用bar 而不是self.bar.

By doing this, one is able to refer to bar instead of self.bar within the scope of Foo.baz().

这样做是错误的还是非pythonic的?

推荐答案

这样做完全没问题.您可能会争辩说您不需要 这样做(至少在您的示例中,如果您不使用局部变量,您可以将方法减少到两行),但没有这样做真的没有问题.

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:

  • 创建一个局部变量显然会创建另一个局部变量
  • 为此使用临时局部变量需要更多代码,从而增加了方法的整体复杂性
  • 访问局部变量比访问实例属性更快
  • 只有一个更新实例属性的点使方法更接近原子性(虽然它不会是纯原子的)并避免属性上的中间值
  • 同样,如果访问或修改 self.bar 有副作用,那么只执行一次可能比多次触发它们更可取
  • 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

所有这些影响通常都非常小,根本不重要.然而它们就在那里,并且只是可能它们可能与您相关.在此之前,请使用您最喜欢的.

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.

这篇关于将类实例变量分配给 Python 方法中的局部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆