函数的 Python 'self'

标签 python idioms self

我已阅读 the SO post关于“ self ”的解释,我已经阅读了Python documentation在类里面。我想我理解 self 在 Python 类中的使用以及其中的约定。

但是,作为 Python 及其习语的新手,我不明白为什么有些人在过程类型函数定义中使用 self。例如,在 Python documentation on integer types ,示例函数为:

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

num替换self是相同的功能结果;即:

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 而不是描述性参数名称?

最佳答案

在示例中,bit_length 被定义为 int 类的函数,因此实际上存在一个“类或方法”。这个想法是你“要求”一个整数来给出它的 bit_length,因此它被定义为将 self 作为参数。

关于函数的 Python 'self',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4250222/

相关文章:

python - 如何修复 "DeprecationWarning: You passed a bytestring as ` 文件名`”?

python - 如何使用 python pandas 从 docker 容器访问 CSV 文件(位于电脑硬盘中)?

algorithm - 惯用 Go 中 set 的最小值

java - GLOB 在 Unix/Linux/Java 世界中的缩写是什么?

python - 为什么使用外部函数传递和更改类自变量可以操作可迭代对象,但不能操作变量?

python - 取消引用 numpy 数组或列表的 void 指针

coding-style - 在 python 中循环使用条件

使用 self 的 C 结构

Python - 类中的Timeit

python - Cython 中的错误消息 "Cannot convert <type_name>* to Python object"