【发布时间】:2011-05-14 02:35:40
【问题描述】:
我已经阅读了关于“自我”的the SO post 解释,并且我已经阅读了关于课程的Python documentation。我想我了解在 Python 类中使用 self 以及其中的约定。
但是,对于 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
将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 而不是描述性参数名称?
【问题讨论】:
-
你可以在这里找到答案 - stackoverflow.com/questions/5067604/…