是否有任何有意义的区别:
class A(object):
foo = 5 # some default value
Run Code Online (Sandbox Code Playgroud)
与
class B(object):
def __init__(self, foo=5):
self.foo = foo
Run Code Online (Sandbox Code Playgroud)
如果您要创建大量实例,那么这两种样式的性能或空间要求是否存在差异?当您阅读代码时,您是否认为两种样式的含义有显着差异?
我创建了以下示例以了解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的副本?