Instances in python

前端 未结 5 794
日久生厌
日久生厌 2021-01-25 15:47

I created the following example to understand the instances in python

import time;
class test:
    mytime = time.time();   
    def __init__(self):
        #self         


        
5条回答
  •  爱一瞬间的悲伤
    2021-01-25 16:22

    let's uncomment "self.mytime = time.time()" line from your code:

    class test:
        mytime = time.time();   
        def __init__(self):
            self.newtime = time.time();
            time.sleep(1);
            #pass - no use of pass here
    
    
    test1 = test()
    test2 = test()
    
    print test1.mytime
    o/p: 1347883057.638443
    print test2.mytime
    o/p: 1347883057.638443
    

    In this case, "mytime" variable is like static class member. and all instances of test() class (i.e: test1 and test2) will share same value of class attributes.

    print test1.newtime
    o/p: 1347883063.421356
    
    print test2.newtime
    o/p: 1347883068.7103591
    

    whereas, value of instance variable. will be different for each instance of class.

    therefore, to get different timing for each instance. you need to declare instance variable using "self" in "init" method.

    • self = instance as a first parameter in class method
    • init = default constructor method in python for defined class

    Hope, it will help.

提交回复
热议问题