参考资料:https://docs.python.org/3/tutorial/classes.html
1. 命名空间 namespace:
Namespaces are created at different moments and have different lifetimes. The namespace containing the built-in names is created when the Python interpreter starts up, and is never deleted. The global namespace for a module is created when the module definition is read in; normally, module namespaces also last until the interpreter quits. The statements executed by the top-level invocation of the interpreter, either read from a script file or interactively, are considered part of a module called __main__, so they have their own global namespace. (The built-in names actually also live in a module; this is called builtins.)
When a class definition is entered, a new namespace is created, and used as the local scope — thus, all assignments to local variables go into this new namespace. In particular, function definitions bind the name of the new function here.
When a class definition is left normally (via the end), a class object is created. This is basically a wrapper around the contents of the namespace created by the class definition; we’ll learn more about class objects in the next section. The original local scope (the one in effect just before the class definition was entered) is reinstated, and the class object is bound here to the class name given in the class definition header (ClassName in the example).
2. 类属性
在类里直接声明的. 只能用ClassA.i 去引用,不能用x=ClassA() x.i 去引用
3. 实例属性(instance attribute)
属于类的实例,不属于类本身.
如上代码,b.z会发生错误.因为z只在a这个实例中声明了,但b这个实例中没有z这个属性.而y这个属性是所有实例都有的实例属性
方法也是一种instance attribute. 方法为什么定义里有个(self)但实际不用加,下面是python文档的解释.
If you still don’t understand how methods work, a look at the implementation can perhaps clarify matters. When a non-data attribute of an instance is referenced, the instance’s class is searched. If the name denotes a valid class attribute that is a function object, a method object is created by packing (pointers to) the instance object and the function object just found together in an abstract object: this is the method object. When the method object is called with an argument list, a new argument list is constructed from the instance object and the argument list, and the function object is called with this new argument list.
4. 继承
Execution of a derived class definition proceeds the same as for a base class. When the class object is constructed, the base class is remembered. This is used for resolving attribute references: if a requested attribute is not found in the class, the search proceeds to look in the base class. This rule is applied recursively if the base class itself is derived from some other class.
多重继承:
多重继承规则搜索时深度优先,从左到右
私有成员:
类变量用两个underscore开头的, 是私有变量,外面一般无法访问.但是如果加_classname__就可以访问到:
上面这个例子说明了私有变量的定义.如果直接引用__开头的名字,引用不到.如果用上图的方法前面加_类名,可以引用到
迭代器
for循环的写法实际上是调用的迭代器方法.类可以自己写自己的迭代器,写完后就能用for 语句循环了
生成器(generator)
这一遍看的不是很理解, 故先不理.常用的一个例子:
网友评论