Python:在方法内部时,类属性是否等同于局部变量?

发布于 2024-09-07 20:33:33 字数 679 浏览 2 评论 0原文

在Python中,我知道查找本地范围的变量比查找全局范围的变量要快得多。 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 慢,当我查看带有属性和方法的类定义时:

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 的使用更像我的第一个或第二个函数吗?如果我子类 Classy 并尝试从子类中的方法访问 attribute2 会怎么样?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

兔小萌 2024-09-14 20:33:33

本地范围的变量速度很快,因为解释器不需要进行字典查找。它在编译时确切地知道将有多少局部变量,并创建指令以数组形式访问它们。

成员属性需要字典查找,因此它们的执行方式与使用全局范围变量的第一个示例类似。

为了提高速度,您可以执行类似以下操作:

attribute1 = self.attribute1
# do stuff with attribute1

在局部变量中隐藏 attribute1,因此只需要一次字典查找。不过,除非我做了一些分析表明某个方法是瓶颈,否则我不会打扰。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文