6
在python中,我知道查找本地作用域变量比查找全局作用域变量要快得多。所以:Python:类方法中的类属性是否等价于局部变量?
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'>
所以,当我看到一个类定义,属性和方法:
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呢?
虽然我一般对这个问题的答案很好奇,但是我问这个问题的真正原因是因为我有一些常量几乎肯定会被一种方法使用,我不确定我是否应该在该方法内或在init内定义它们(以防我后来意识到它们需要在别处访问)。由于这种可能性很小,我想我会在方法中对它们进行定义。谢谢。 – Wilduck 2010-06-30 16:13:06