Python - why use “self” in a class?

后端 未结 5 1097
夕颜
夕颜 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:45

    I've just started learning Python and this confused me as well for some time. Trying to figure out how it all works in general I came up with this very simple piece of code:

    # Create a class with a variable inside and an instance of that class
    class One:
        color = 'green'
    
    obj2 = One()
    
    
    # Here we create a global variable(outside a class suite).
    color = 'blue'         
    
    # Create a second class and a local variable inside this class.       
    class Two:             
        color = "red"
    
        # Define 3 methods. The only difference between them is the "color" part.
        def out(self):     
            print(self.color + '!')
    
        def out2(self):
            print(color + '!')
    
        def out3(self):
            print(obj2.color + '!')
    
    # Create an object of the class One
    obj = Two()
    

    When we call out() we get:

    >>> obj.out()
    
    red!
    

    When we call out2():

    >>> obj.out2()
    
    blue!
    

    When we call out3():

    >>> obj.out3()
    
    green!
    

    So, in the first method self specifies that Python should use the variable(attribute), that "belongs" to the class object we created, not a global one(outside the class). So it uses color = "red". In the method Python implicitly substitutes self for the name of an object we created(obj). self.color means "I am getting color="red" from the obj"

    In the second method there is no self to specify the object where the color should be taken from, so it gets the global one color = 'blue'.

    In the third method instead of self we used obj2 - a name of another object to get color from. It gets color = 'green'.

提交回复
热议问题