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,
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
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:
- When applying the guideline would make the code less readable, even for someone who is used to reading code that follows this PEP.
- 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).
- Because the code in question predates the introduction of the guideline and there is no other reason to be modifying that code.
- When the code needs to remain compatible with older versions of Python that don't support the feature recommended by the style guide.