5

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?

1

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

1 Comment

In other words, the docs show an equivalent (but inefficient) implementation of one of int's methods, that's why it uses self.
4

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.

2 Comments

This. Since methods are just functions (well, mostly) def do_stuff(self): ..., Clazz.do_stuff = do_stuff is pretty much the same as defining a method do_stuff as usual, only more ugly/non-obvious/hacky and therefore not useful except when you're monkey-patching.
-1. Incorrect. The docs show an equivalent implementation of one of int's methods, that's why it uses self.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.