Python Class Members Initialization

前端 未结 5 1768
后悔当初
后悔当初 2020-11-29 03:37

I have just recently battled a bug in Python. It was one of those silly newbie bugs, but it got me thinking about the mechanisms of Python (I\'m a long time C++ programmer,

5条回答
  •  醉话见心
    2020-11-29 04:40

    If this is your code:

    class ClassA:
        dict1 = {}
    a = ClassA()
    

    Then you probably expected this to happen inside Python:

    class ClassA:
        __defaults__['dict1'] = {}
    
    a = instance(ClassA)
    # a bit of pseudo-code here:
    for name, value in ClassA.__defaults__:
        a. = value
    

    As far as I can tell, that is what happens, except that a dict has its pointer copied, instead of the value, which is the default behaviour everywhere in Python. Look at this code:

    a = {}
    b = a
    a['foo'] = 'bar'
    print b
    

提交回复
热议问题