Python类提供了面向对象编程的所有标准特性:类继承机制允许多个基类,派生类可以重写其基类的任何方法,子类方法可以调用具有相同名称的基类的方法。对象可以包含任意数量和种类的数据(Objects can contain arbitrary amounts and kinds of data)。
用C++的术语,Python的类成员(包括数据成员)是公共的(除了下面的私有变量之外,在Python中可以通过在属性变量名前加上双下划线定义属性为private;添加_变成protected),并且所有成员函数都是虚拟的。
虚函数:A virtual function is a member function which is declared within a base class and is re-defined(Overriden) by a derived class. When you refer to a derived class object using a pointer or a reference to the base class, you can call a virtual function for that object and execute the derived class’s version of the function.
类就像一个对象构造函数,或者是创建对象的“蓝图”。(A Class is like an object constructor, or a "blueprint" for creating objects.).
class MyClass: x1 = 5 p1 = MyClass() print(p1.x1) class Child(MyClass): x2 = 6 c2 = Child() print(c2.x1) print(c2.x2)
In Python, class is an executable statement. When the interpreter finds a class statement, then first all the code in the class statement block is executed (in a special namespace), then all names defined in that block are used to build the class object (Python classes are objects), and finally 类属性 is bound to the class object in the current scope.
断点调试,程序先执行到2行,说明 class is an executable statement, 所有类内代码会按照脚本执行顺序依次执行. x1=5 会保存到MyClass class object 的命名空间中.执行到5和6行,用MyClass创建p1和p2两个实例的时候,会拷贝MyClass class object 的命名空间到p1和p2的object的命名空间内.此后,p1和p2两个object的命名空间彼此互相独立互不干扰.
所以,执行到第9行时,p1.x1被改为4,可是p2的x1还是初始值5.
继续向下执行,当执行完13行的时候,发现新创建的Child Class Object内部不光有属性x2=6,还有从
父亲MyClass Class Object命名空间里面拷贝过来的x1=5.
继续向下执行,当执行完16行的时候,c2 Object的命名空间直接用Child Class Object的命名空间复制生成,所以最后两行打印如下:
5
6
命名空间:A namespace is a mapping from names to objects. Examples of namespaces are: the set of built-in names (containing functions such as abs(), and built-in exception names); the global names in a module; and the local names in a function invocation. The set of attributes of an object also form a namespace.
名称空间是在不同的时刻创建的,具有不同的生命周期。包含内置名称的名称空间是在Python解释器启动时创建的,并且永远不会被删除。在读入模块定义时创建模块的全局命名空间;通常,模块名称空间也会持续到解释器退出。解释器的顶级调用执行的语句(从脚本文件读取或以交互方式执行)被视为名为_main__的模块的一部分,因此它们有自己的全局名称空间。(内置名称实际上也存在于模块中;这称为内置名称。)
虽然命名空间是静态定义的,但它们是动态使用的。在执行过程中的任何时候,都有3或4个嵌套作用域的命名空间可以直接访问
关于The __init__() Function
the __init__() function to assign values to object properties, or other operations that are necessary to do when the object is being created.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("John", 36)
print(p1.name)
print(p1.age)
__init__()方法在执行类定义的时候不会具体的执行(只会定义),所以里面定义的属性不是类的属性,仅仅是类实例的动态属性,所以不会被子类继承或覆盖.
参考:
9. Classes — Python 3.9.7 documentationhttps://docs.python.org/3/tutorial/classes.html
https://www.w3schools.com/python/python_classes.asphttps://www.w3schools.com/python/python_classes.asp



