A class definition defines a class object (see section 3.2):
一个类定义定义一个类对象(见3.2节)
classdef |
::= | "class" classname [inheritance] ":"
suite |
inheritance |
::= | "(" [expression_list] ")" |
classname |
::= | identifier |
A class definition is an executable statement. It first evaluates the inheritance list, if present. Each item in the inheritance list should evaluate to a class object or class type which allows subclassing. The class's suite is then executed in a new execution frame (see section 4.1), 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. The class name is bound to this class object in the original local namespace.
一个类定义是一个可以执行语句. 它首先考察继承关系表,如果存在. 在继承关系表中的每个对象都生成一个类对象.然后类的语句序列在新的堆栈结构(见4.1节)使用新创建的局部名字空间和原来的全局名字空间执行.(通常这个语句序列仅仅包括函数定义)当该类的语句序执行结束后就丢弃掉这个堆栈结构但该局部名字空间会被保存下来.然后便使用其继承关系表创建基类和保存下来的名字空间作为属性字典创建新的类对象.在最初的名字空间中, 类的名字绑定在这个类对象上.
Programmer's note: Variables defined in the class definition
are class variables; they are shared by all instances. To define
instance variables, they must be given a value in the
__init__() method or in another method. Both class and
instance variables are accessible through the notation
``self.name
'', and an instance variable hides a class variable
with the same name when accessed in this way. Class variables with
immutable values can be used as defaults for instance variables.
For new-style classes, descriptors can be used to create instance
variables with different implementation details.
程序员注意:在类定义中定义的变量是类变量; 它们共享所有的类实例, 为了定义变量, 它们必须在__init__()或其它方法中被指定一个值.所有类变量和实例变量都可以通过"self.name"记号访问, 并且实例变量如果和类变量重名, 此时会隐藏类变量.具有不可变值的类变量可以作为实例变量的默认值.