Python“自我”为了功能
我已阅读SO post关于“自我”的解释,并且我已阅读有关类的 Python 文档。我想我理解了 Python 类中 self 的使用以及其中的约定。
然而,由于对 Python 及其习惯用法相对较新,我无法理解为什么有些人在过程类型函数定义中使用 self 。例如,在 有关整数类型的 Python 文档,示例函数为:
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
将self
替换为num
,函数结果相同;即:
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
没有像 __init__
等习语,我可以在这里看到为什么在第一种情况下使用 self
。我在过程函数的其他地方也看到过这种使用 self
的情况,并且发现它令人困惑。
所以我的问题是:如果没有类或方法,为什么在函数定义中使用 self 而不是描述性参数名称?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在示例中,bit_length 被定义为 int 类的函数,因此实际上存在一个“类或方法”。这个想法是你“要求”一个整数给出它的 bit_length,因此它被定义为以 self 作为参数。
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.