【发布时间】:2018-03-07 13:18:40
【问题描述】:
所以在 python 的 docutils 包中有一个类 (Image) 有一个方法 (align)。据我了解,除非将它们装饰为@classmethod 或@staticmethod,否则方法将self 作为第一个参数,但是align 不会。相关代码复制如下(full code here)。
class Image(Directive):
def align(argument):
# This is not callable as self.align. We cannot make it a
# staticmethod because we're saving an unbound method in
# option_spec below.
return directives.choice(argument, Image.align_values)
我将此代码用作我自己的目的的基础,并且我尝试过给 align 一个 self 参数并将其转换为静态方法(在更改名称以免与 self.align 冲突之后),但无论哪种方法都有错误。怎么回事?
【问题讨论】:
-
您能提供您遇到的错误吗?
-
with @staticmethod: 'staticmethod' 对象不可调用。添加了“self”:align_option() 缺少 1 个必需的位置参数:“arg”。
-
实际上这是记录在案的:“这不能作为 self.align 调用。我们不能将其设为静态方法,因为我们在下面的 option_spec 中保存了一个未绑定的方法。”
-
文档不是很清楚,但是。我读到了,我的第一个想法是“如果它不是方法,你为什么要定义函数?”我花了一段时间才意识到该函数(至少,通过类属性访问)不打算在类外使用。
标签: python class static-methods