difference between variables inside and outside of __init__()

前端 未结 10 779
醉酒成梦
醉酒成梦 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:38

    Without Self

    Create some objects:

    class foo(object):
        x = 'original class'
    
    c1, c2 = foo(), foo()
    

    I can change the c1 instance, and it will not affect the c2 instance:

    c1.x = 'changed instance'
    c2.x
    >>> 'original class'
    

    But if I change the foo class, all instances of that class will be changed as well:

    foo.x = 'changed class'
    c2.x
    >>> 'changed class'
    

    Please note how Python scoping works here:

    c1.x
    >>> 'changed instance'
    

    With Self

    Changing the class does not affect the instances:

    class foo(object):
        def __init__(self):
            self.x = 'original self'
    
    c1 = foo()
    foo.x = 'changed class'
    c1.x
    >>> 'original self'
    

提交回复
热议问题