Python - why use “self” in a class?

后端 未结 5 1096
夕颜
夕颜 2020-11-28 19:56

How do these 2 classes differ?

class A():
    x=3

class B():
    def __init__(self):
        self.x=3

Is there any significant difference?

5条回答
  •  爱一瞬间的悲伤
    2020-11-28 20:29

    I used to explain it with this example

    # By TMOTTM
    
    class Machine:
    
        # Class Variable counts how many machines have been created.
        # The value is the same for all objects of this class.
        counter = 0
    
        def __init__(self):
    
            # Notice: no 'self'.
            Machine.counter += 1
    
            # Instance variable.
            # Different for every object of the class.
            self.id = Machine.counter
    
    if __name__ == '__main__':
        machine1 = Machine()
        machine2 = Machine()
        machine3 = Machine()
    
        #The value is different for all objects.
        print 'machine1.id', machine1.id
        print 'machine2.id', machine2.id
        print 'machine3.id', machine3.id
    
        #The value is the same for all objects.
        print 'machine1.counter', machine1.counter
        print 'machine2.counter', machine2.counter
        print 'machine3.counter', machine3.counter
    

    The output then will by

    machine1.id 1
    machine2.id 2
    machine3.id 3
    
    machine1.counter 3
    machine2.counter 3
    machine3.counter 3
    

提交回复
热议问题