python 类 中的实例方法和静态方法

instance methods and static methods in python classes

所以在 python 的 docutils 包中有一个 class (Image) 有一个方法 (align)。据我了解,方法将 self 作为第一个参数,除非它们被装饰为 @classmethod 或 @staticmethod,但是 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), 但是这两种方法都出错了。这是怎么回事?

不需要命名第一个参数self;那只是一个惯例。在下面的代码中

i = Image()
i.align()

将使用参数 argument 引用对象 i.

调用 align 方法

以下函数的行为相同:

def align(self):
    return directives.choice(self, Image.align_values)

(简单地将 argument 替换为更常见的 self)。


在上下文中,函数 align 从未打算成为一种方法;作者似乎只是在定义一个存储在 options_spec 字典中的函数。通过在保存函数引用后删除名称,可以在不污染 class 的命名空间的情况下达到预期的效果:

option_spec = {'alt': directives.unchanged,
               'height': directives.length_or_unitless,
               'width': directives.length_or_percentage_or_unitless,
               'scale': directives.percentage,
               'align': align,
               'name': directives.unchanged,
               'target': directives.unchanged_required,
               'class': directives.class_option}
del align

或者放弃 def 语句——这是一个非常简单的函数——并使用 lambda 表达式来创建函数。

option_spec = {'alt': directives.unchanged,
               'height': directives.length_or_unitless,
               'width': directives.length_or_percentage_or_unitless,
               'scale': directives.percentage,
               'align': lambda x: directives.choice(x, Image.align_values)
               'name': directives.unchanged,
               'target': directives.unchanged_required,
               'class': directives.class_option}