Python - why use “self” in a class?

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

    Just as a side note: self is actually just a randomly chosen word, that everyone uses, but you could also use this, foo, or myself or anything else you want, it's just the first parameter of every non static method for a class. This means that the word self is not a language construct but just a name:

    >>> class A:
    ...     def __init__(s):
    ...        s.bla = 2
    ... 
    >>> 
    >>> a = A()
    >>> a.bla
    2
    

提交回复
热议问题