Search code examples
pythonself

Naming the self parameter something else


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 might already have noticed, the self parameter is named me in the __init__ method, myself in the print_foo method and i in the set_foo method.

Is there a situation in which naming the self parameter something other than self is useful? If not, why does Python allow this, as it is certainly a way to write a code that is difficult to read and to maintain, and also a source of confusion?


Solution

  • PEP 8 addresses this pretty clearly:

    Always use self for the first argument to instance methods.

    Always use cls for the first argument to class methods.

    Although remember that being the python style guide this is not enforced

    However, know when to be inconsistent -- sometimes style guide recommendations just aren't applicable. When in doubt, use your best judgment. Look at other examples and decide what looks best.

    Sometimes, like in fractions.py in the standard library, it might be clearer to you to use something like a,b instead of self,other because <your specific reasons>

    the style guide actually lists a few reasons you might break usual convention right below the above quote:

    Some other good reasons to ignore a particular guideline:

    1. When applying the guideline would make the code less readable, even for someone who is used to reading code that follows this PEP.
    2. To be consistent with surrounding code that also breaks it (maybe for historic reasons) -- although this is also an opportunity to clean up someone else's mess (in true XP style).
    3. Because the code in question predates the introduction of the guideline and there is no other reason to be modifying that code.
    4. When the code needs to remain compatible with older versions of Python that don't support the feature recommended by the style guide.