开发者

Python 'self' for function

开发者 https://www.devze.com 2023-01-26 04:09 出处:网络
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.

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 sig开发者_JS百科n
    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?


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消