gpt4 book ai didi

python-3.x - 为什么这两个类在 python 3.x 中执行,它们只是定义了?

转载 作者:行者123 更新时间:2023-12-04 08:10:56 24 4
gpt4 key购买 nike

为什么要执行这两个类?我刚刚定义了两个基类。我没用f = F ()g = G ()实例化对象。为什么要执行两次打印?

class F():
print("F.__new__called")

class G:
print("G.__new__called")

print("test")
输出:
F.__new__called
G.__new__called
test

最佳答案

如 Python 3 文档 9.3.1 "Class Definition Syntax" (强调我的):

The simplest form of class definition looks like this:

class ClassName:
<statement-1>
.
.
.
<statement-N>

Class definitions, like function definitions (def statements) must be executed before they have any effect. (You could conceivably place a class definition in a branch of an if statement, or inside a function.)

In practice, the statements inside a class definition will usually be function definitions, but other statements are allowed, and sometimes useful — we’ll come back to this later. The function definitions inside a class normally have a peculiar form of argument list, dictated by the calling conventions for methods — again, this is explained later.


就 Python 而言, class 中允许任何语句。定义,甚至超出典型的属性分配和功能定义。这些语句立即运行,与 def 的含义相同。必须运行语句才能定义函数。
(文档显然没有回到 block 中其他语句的实用性,尽管其他示例在 9.6 代码块中交错了私有(private)变量引用的赋值。)
但是,与您的打印语句的内容不同,这些不对应于“F.__new__call”;它只对应于被定义的类。当您调用 f = F () , Python 将调用方法 __new____init__ ,然后负责构造对象。

关于python-3.x - 为什么这两个类在 python 3.x 中执行,它们只是定义了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65965683/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com