Python: Are class attributes equivalent to local variables when inside a method?
In python, I know that lo开发者_如何学Pythonoking up a locally scoped variable is significantly faster than looking up a global scoped variable. So:
a = 4
def function()
for x in range(10000):
<do something with 'a'>
Is slower than
def function()
a = 4
for x in range(10000):
<do something with 'a'>
So, when I look at a class definition, with an attribute and a method:
class Classy(object):
def __init__(self, attribute1):
self.attribute1 = attribute1
self.attribute2 = 4
def method(self):
for x in range(10000):
<do something with self.attribute1 and self.attribute2>
Is my use of self.attribute more like my first or second function? What about if I sub class Classy, and try to access attribute2 from a method in my sub class?
Locally scoped variables are fast because the interpreter doesn't need to do a dictionary lookup. It knows at compile-time exactly how many local variables there will be and it creates instructions to access them as an array.
Member attributes require a dictionary lookup, so they execute similar to your first example using globally scoped variables.
For speed, you can do something like:
attribute1 = self.attribute1
# do stuff with attribute1
which shadows attribute1 in a local variable, so only a single dictionary lookup is needed. I wouldn't bother unless I'd done some profiling indicating that a method was a bottleneck, though.
精彩评论