Python的:有上课的时候​​在方法内部属性等同于局部变量? [英] Python: Are class attributes equivalent to local variables when inside a method?

查看:90
本文介绍了Python的:有上课的时候​​在方法内部属性等同于局部变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在蟒蛇,我知道,找了一个本地变量比寻找一个全球范围的变量显著更快。所以:

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'>

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>

是我的使用self.attribute更像我的第一或第二功能?那么如果我子类优等,并尝试从一个方法访问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?

推荐答案

本地范围的变量是快,因为跨preTER并不需要做一个字典查找。它在编译时知道到底有多少局部变量会有和它创造的指令访问它们作为数组。

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

这阴影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.

这篇关于Python的:有上课的时候​​在方法内部属性等同于局部变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆