问题
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()
.
Is it wrong, or Unpythonic, to do this?
回答1:
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
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.
来源:https://stackoverflow.com/questions/44200715/assign-a-class-instance-variable-to-a-local-variable-within-a-method-in-python