[英]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: 有某些结果可能最终使一种或另一种方法更可取:
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.