Self-naming parameter naming

In Python, this code is valid:

class A:

    def __init__(me):
        me.foo = 17

    def print_foo(myself):
        print(myself.foo)

    def set_foo(i, v):
        i.foo = v

As you already noticed, the parameter selfhas a name mein the method __init__, myselfin the method print_fooand iin the method set_foo.

Is there a situation where assigning a parameter selfto something other than selfuseful? If not, why does Python allow this, since it is certainly a way to write code that is difficult to read and maintain, and also a source of confusion?

+4
source share
4 answers

PEP 8 pretty clearly describes this:

Always use self for the first argument to instance methods.

Always use cls for the first argument to class methods.

, python

, , - . , . , .

, fractions.py, - a,b self,other, <your specific reasons>

, :

:

  • , , PEP.
  • , (, ) - ( XP).
  • , .
  • Python, , .
+3

: " , ? - , - , , : , self . ( , self - -, .)

, Python ? : , self ( ) self , this .

: python ( , , yield from, from ... import while ... else). , - , , .

, self , , ? locals() "" , : " , ". , self , , , . . ( Guido : " , @classmethod @staticmethod Python".) , .

+2

self , . cls this.

self python, , , Java. - , , - .

+1

Guido van Rossum . Spesifically:

I see no reason with this proposal to make "I" a reserved word or to require that the prefix name be exactly "I".

This is just an agreement, and it's nice to stick to it.

+1
source

All Articles