Instances in python

前端 未结 5 836
日久生厌
日久生厌 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:33

    The mytime variable is first created as a class variable and not an instance variable.

    Python tries to locate a name on an instance first and if it is not found it will lookup the name on the class. You can query the namespace of any object (including) classes by looking at the object's __dict__, which is a dictionary containing the instance variables.

    As soon as you set test1.mytime = 12, you created a new name in that object's __dict__, which from then on shadowed the class variable with the same name.

提交回复
热议问题