I have read the SO post on 'self' explained, and I have read the Python documentation on classes. I think I understand the use of self
in Python classes and the convention therein.
However, being relatively new to Python and its idioms, I cannot understand why some use self
in a procedural type function definition. For example, in the Python documentation on integer types, the example function is:
def bit_length(self):
s = bin(self) # binary representation: bin(-37) --> '-0b100101'
s = s.lstrip('-0b') # remove leading zeros and minus sign
return len(s) # len('100101') --> 6
Replacing self
with num
is the same functional result; ie:
def bit_length(num):
s = bin(num) # binary representation: bin(-37) --> '-0b100101'
s = s.lstrip('-0b') # remove leading zeros and minus sign
return len(s) # len('100101') --> 6
There is no idiom like __init__
etc that I can see here why self
is being used in the first case. I have seen this use of self
elsewhere in procedural functions as well, and find it confusing.
So my question: If there is no class or method, why use self
in a function definition rather than a descriptive parameter name?