[英]Assign a class instance variable to a local variable within a method in Python
可以将类实例变量分配给方法中的局部变量,例如:
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
。
这样做是错误的还是Unpythonic?
这样做非常好。 您可能会争辩说您不需要这样做(至少在您的示例中,如果您不使用局部变量,则可以将方法减少到两行),但是这样做确实没有任何问题。
有某些结果可能最终使一种或另一种方法更可取:
self.bar
有副作用,那么最好只执行一次,而不是多次触发它们。 所有这些影响通常都是极小的, 根本没关系 。 但是它们在那里, 也许它们可能与您息息相关。 在此之前,请使用最舒适的东西。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.