类中的条件语句,但不在函数范围内 [英] Conditional statements in a class, but outside of scope of the function

查看:101
本文介绍了类中的条件语句,但不在函数范围内的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们知道用符号表示:

class Foo(object):

    a = 1

    def __init__(self):
        self.b = 2

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

我们可以创建静态变量 Foo.a ,正常变量 b ,在创建 Foo 和方法 c

we can create static variable Foo.a, 'normal' variable b, which will be available after creating and instance of Foo, and method c

今天我真的很惊讶,我可以在一个类中使用条件语句,但是超出了函数范围

Today I was really surprised, that I can use conditional statements in a class, but outside of scope of the function

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

像C ++ / Java这样的语言告诉我,法律表示法类似于:

Languages like C++/Java, taught me that legal notation is similar to:

class Name():
    variable = <expression>

您能描述其他涉及此特定范围的规则吗?我应该如何命名该范围?

Could you describe other rules, which refer to this specific scope? How I should name this scope?

推荐答案

类主体是 just Python code 。它具有特定的作用域规则,但其他方面则没有。这意味着您可以有条件地创建函数:

The class body is just Python code. It has specific scope rules, but anything goes otherwise. This means you can create functions conditionally:

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

或从其他地方提取方法:

or pull methods from elsewhere:

import some_module

class D:
    method_name = some_module.function_that_accepts_self

等。

class 定义状态:


类定义是可执行语句。

A class definition is an executable statement.


然后在新的执行框架中执行该类的套件(请参见 命名和绑定 ),使用新创建的d本地名称空间和原始全局名称空间。 (通常,套件仅包含函数定义。)当类的套件完成执行时,其执行框架将被丢弃,但其本地名称空间将被保存。然后,使用基类的继承列表和属性字典的已保存本地名称空间创建类对象。

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.

请注意该文本中的通常。本质上,类主体是按函数执行的,并且您放入主体命名空间中的任何内容都将成为该类的属性。

Note the usually in that text. Essentially, the class body is executed as a function would, and anything you put in the body namespace becomes an attribute on the class.

命名和绑定 部分会告诉您:

The Naming and binding section then tells you:


在类块中定义的名称范围仅限于该类块;它不会扩展到方法的代码块

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

,因此您不能在方法中直接访问在此块中定义的名称;您应该使用 class.name self.name

so names you define in this block cannot be directly accessed in methods; you'd use class.name or self.name instead.

这篇关于类中的条件语句,但不在函数范围内的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆