为什么 class 定义需要比函数定义更多的属性信息?

Why class definition needs more information of its attributes than what is needed in a function definition?

def myfunc():
    return x
x = 10
print(myfunc())

以上代码有效,我定义myfunc.

时不需要定义自由变量x

但是,以下代码不起作用:

class myclass:
   func = extfunc

def extfunc(self):
    return 'hello'

这里我需要将 extfunc 的定义移到 class 定义之前,以使代码正常工作。

为什么 class 定义比函数定义中的自由变量需要更多的属性信息?

此代码:

def myfunc():
    return x

定义一个函数,但不执行里面的代码x是until/unlessmyfunc被调用。函数的 body 在计算函数定义时不计算,它在 later 调用函数时计算。

相比之下,在这段代码中:

class myclass:
    func = extfunc

评估 class 定义以创建 class,如文档 here 中所述。因此 func = extfunc 被评估为 class 定义的一部分,以便为 class 范围内的 func 变量赋值。 func 就像使用该术语的语言中的静态成员。

更直接的比较是这样的:

class myclass:
    def example(self):
        return x

在那里,直到或除非 example 被调用,return x 才被评估。

另请参阅文档中的 this example

Attribute references use the standard syntax used for all attribute references in Python: obj.name. Valid attribute names are all the names that were in the class’s namespace when the class object was created. So, if the class definition looked like this:

class MyClass:
    """A simple example class"""
    i = 12345

    def f(self):
        return 'hello world'

then MyClass.i and MyClass.f are valid attribute references, returning an integer and a function object, respectively.

在您的示例中,myclass.func 将是紧跟在 class 定义之后的有效引用,因此 func = extfunc 必须在 期间 class 定义,不像函数体。