gpt4 book ai didi

python - 类中的条件语句,但在函数范围之外

转载 作者:太空狗 更新时间:2023-10-29 20:15:38 25 4
gpt4 key购买 nike

我们知道用符号:

class Foo(object):

a = 1

def __init__(self):
self.b = 2

def c(self):
print('c')

我们可以创建静态变量Foo.a,'普通'变量b,在创建Foo实例后可用,和方法c

今天我真的很惊讶,我可以在类中使用条件语句,但在函数范围之外

class C():
if True:
a = 1
b = 2

像 C++/Java 这样的语言,告诉我合法的符号类似于:

class Name():
variable = <expression>

您能否描述其他适用于该特定范围的规则?我应该如何命名这个范围?

最佳答案

类主体只是 Python 代码。它有特定的范围规则,但一切都不一样。这意味着您可以有条件地创建函数:

class C:
if some_condition:
def optional_method(self):
pass

或者从别处拉取方法:

import some_module

class D:
method_name = some_module.function_that_accepts_self

等等

class definitions 的 Python 文档状态:

A class definition is an executable statement.

The class’s suite is then executed in a new execution frame (see section Naming and binding), using a newly created local namespace and the original global namespace. (Usually, the suite contains only function definitions.) When the class’s suite finishes execution, its execution frame is discarded but its local namespace is saved. A class object is then created using the inheritance list for the base classes and the saved local namespace for the attribute dictionary.

注意该文本中的通常。本质上,类主体的执行就像函数一样,您放入主体 namespace 中的任何内容都将成为类的属性。

Naming and binding然后部分告诉你:

The scope of names defined in a class block is limited to the class block; it does not extend to the code blocks of methods

因此您在此 block 中定义的名称不能在方法中直接访问;您将使用 class.nameself.name 代替。

关于python - 类中的条件语句,但在函数范围之外,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27230680/

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