difference between variables inside and outside of __init__()

前端 未结 10 770
醉酒成梦
醉酒成梦 2020-11-22 17:08

Is there any difference at all between these classes besides the name?

class WithClass ():
    def __init__(self):
        self.value = \"Bob\"
    def my_fu         


        
10条回答
  •  一生所求
    2020-11-22 17:41

    class foo(object):
        mStatic = 12
    
        def __init__(self):
            self.x = "OBj"
    

    Considering that foo has no access to x at all (FACT)

    the conflict now is in accessing mStatic by an instance or directly by the class .

    think of it in the terms of Python's memory management :

    12 value is on the memory and the name mStatic (which accessible from the class)

    points to it .

    c1, c2 = foo(), foo() 
    

    this line makes two instances , which includes the name mStatic that points to the value 12 (till now) .

    foo.mStatic = 99 
    

    this makes mStatic name pointing to a new place in the memory which has the value 99 inside it .

    and because the (babies) c1 , c2 are still following (daddy) foo , they has the same name (c1.mStatic & c2.mStatic ) pointing to the same new value .

    but once each baby decides to walk alone , things differs :

    c1.mStatic ="c1 Control"
    c2.mStatic ="c2 Control"
    

    from now and later , each one in that family (c1,c2,foo) has its mStatica pointing to different value .

    [Please, try use id() function for all of(c1,c2,foo) in different sates that we talked about , i think it will make things better ]

    and this is how our real life goes . sons inherit some beliefs from their father and these beliefs still identical to father's ones until sons decide to change it .

    HOPE IT WILL HELP

提交回复
热议问题