difference between variables inside and outside of __init__()

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

    Example code:

    class inside:
        def __init__(self):
            self.l = []
    
        def insert(self, element):
            self.l.append(element)
    
    
    class outside:
        l = []             # static variable - the same for all instances
    
        def insert(self, element):
            self.l.append(element)
    
    
    def main():
        x = inside()
        x.insert(8)
        print(x.l)      # [8]
        y = inside()
        print(y.l)      # []
        # ----------------------------
        x = outside()
        x.insert(8)
        print(x.l)      # [8]
        y = outside()
        print(y.l)      # [8]           # here is the difference
    
    
    if __name__ == '__main__':
        main()
    

提交回复
热议问题