har*_*les 1 python oop python-3.x
可以将类实例变量分配给方法内的局部变量,例如:
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
Run Code Online (Sandbox Code Playgroud)
通过这样做,人们可以参考bar而不是self.bar在 的范围内Foo.baz()。
这样做是错误的还是Unpythonic?
这样做完全没问题。您可能会争辩说您不需要这样做(至少在您的示例中,如果不使用局部变量,您可以将方法减少到两行),但这样做并没有任何问题。
有某些效果可能最终使一种或另一种方式更可取:
self.bar有副作用,那么只执行一次可能比多次触发它们更可取所有这些影响通常都非常小,根本不重要。然而,它们就在那里,也许它们可能与您相关。在此之前,请使用您最喜欢的东西。