Why do pythonistas call the current reference “self” and not “this”?

后端 未结 8 1682
终归单人心
终归单人心 2020-12-13 12:13

Python is the language I know the most, and strangely I still don\'t know why I\'m typing \"self\" and not \"this\" like in Java or PHP.

I know that Python is older

8条回答
  •  粉色の甜心
    2020-12-13 12:59

    With respect to python, there is nothing special about self. You can use this instead if you wanted:

    Here's an example:

    >>> class A(object):
    ...    def __init__(this):
    ...       this.x = 3
    ... 
    >>> a = A()
    >>> a.x
    3
    

    Although you could name it whatever you want, self is the convention for the first argument of a class function. Check out paragraph 5 of section 9.4 in the python documentation, which says:

    Often, the first argument of a method is called self. This is nothing more than a convention: the name self has absolutely no special meaning to Python. Note, however, that by not following the convention your code may be less readable to other Python programmers, and it is also conceivable that a class browser program might be written that relies upon such a convention.

    As for the convention, it started out in Smalltalk, but is also used in Object Pascal, Python, Ruby, and Objective-C. This answer has a great explanation.

提交回复
热议问题