相关疑难解决方法(0)

类和实例属性有什么区别?

是否有任何有意义的区别:

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 attributes member-variables

127
推荐指数
4
解决办法
6万
查看次数

python中的实例

我创建了以下示例以了解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的副本?

python class

1
推荐指数
1
解决办法
3546
查看次数

标签 统计

python ×2

attributes ×1

class ×1

member-variables ×1