Python: Are class attributes equivalent to local variables when inside a method?

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-06 02:16:30

问题


In python, I know that looking 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?


回答1:


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.



来源:https://stackoverflow.com/questions/3151068/python-are-class-attributes-equivalent-to-local-variables-when-inside-a-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!