实例在python [英] Instances in python

查看:101
本文介绍了实例在python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了以下示例来了解python中的实例

I created the following example to understand the instances in 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

在这种情况下,输出ID如下:

in this case the output id the following:

1347876794.72
1347876794.72
12
1347876794.72

我预计test2.mytime比test1.mytime大1秒。为什么不在每个实例中创建关于mytime的副本?

I expected that the test2.mytime is bigger with 1 second than the test1.mytime. Why doesn't created a copy about the mytime in each instance?

推荐答案

让我们看看这些行:

class test:
   mytime = time.time();   

在此设置类成员值 ,因此当加载包含 class test 的模块时,将计算一次 time.time()

Here you set class member value, which is calculated once when class definition is executed, so time.time() is calculated once when module that contains class test is loaded.

类测试的每个实例都将接收到该预先计算的值,并且必须覆盖该值(例如,在__init__方法中)它通过 self (这是存储对实例的引用的特殊参数),从而设置实例成员值

Every instance of the class test will receive that precalculated value and you must override that value (e.g. in __init__ method), accessing it via self (which is a special argument that stores reference to an instance), thus setting instance member value.

这篇关于实例在python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆