我创建了以下示例以了解python中的实例
import time;
class test:
mytime = time.time();
def __init__(self):
#self.mytime = time.time();
time.sleep(1);
pass
from test import test
test1 = test()
test2 = test()
print test1.mytime
print test2.mytime
test1.mytime = 12
print test1.mytime
print test2.mytime
Run Code Online (Sandbox Code Playgroud)
在这种情况下输出id如下:
1347876794.72
1347876794.72
12
1347876794.72
Run Code Online (Sandbox Code Playgroud)
我期望test2.mytime比test1.mytime大1秒.为什么不在每个实例中创建关于mytime的副本?
让我们看看这些线:
class test:
mytime = time.time();
Run Code Online (Sandbox Code Playgroud)
在这里设置类成员值,该值在执行类定义时计算一次,因此time.time()在class test加载包含的模块时计算一次.
的每个实例class test将接收到的预先计算的值,并且必须覆盖该值(例如,在__init__方法),通过访问它self(这是存储参考实例的特殊参数),从而设置实例成员值.
| 归档时间: |
|
| 查看次数: |
3546 次 |
| 最近记录: |