Question

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?

Was it helpful?

Solution

In the example bit_length is defined as a function for the int class, so there is actually a 'class or method'. The idea is that you 'ask' an integer to give its bit_length, hence it is defined to take self as an argument.

OTHER TIPS

No real reason. But if you're going to monkeypatch it onto an existing class then it acts as a bit of notification for anyone that may be reading the code.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top