Python:在方法内部时,类属性是否等同于局部变量?
在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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
本地范围的变量速度很快,因为解释器不需要进行字典查找。它在编译时确切地知道将有多少局部变量,并创建指令以数组形式访问它们。
成员属性需要字典查找,因此它们的执行方式与使用全局范围变量的第一个示例类似。
为了提高速度,您可以执行类似以下操作:
在局部变量中隐藏 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:
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.