Python“自我”为了功能

发布于 2024-10-03 11:34:59 字数 1184 浏览 1 评论 0原文

我已阅读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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

一袭白衣梦中忆 2024-10-10 11:34:59

在示例中,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.

鸵鸟症 2024-10-10 11:34:59

没有真正的原因。但是,如果您要将其猴子补丁到现有的类上,那么它可以为可能正在阅读代码的任何人提供一些通知。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文