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?

Community
  • 1
  • 1
dawg
  • 98,345
  • 23
  • 131
  • 206
  • You can find an answer here - https://stackoverflow.com/questions/5067604/determine-function-name-from-within-that-function-without-using-traceback – Vasin Yuriy Oct 15 '19 at 09:28

2 Answers2

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.

Lucas Moeskops
  • 5,445
  • 3
  • 28
  • 42
  • 2
    In other words, the docs show an equivalent (but inefficient) implementation of one of `int`'s methods, that's why it uses `self`. – Steven Rumbalski Nov 22 '10 at 21:18
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.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
  • 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. –  Nov 22 '10 at 21:10
  • 1
    -1. Incorrect. The docs show an equivalent implementation of one of `int`'s methods, that's why it uses `self`. – Steven Rumbalski Nov 22 '10 at 21:16