关于 class、sub class 和使用 python 编程中的属性的概念性问题

Conceptual questions about class, sub class and attributes in programming using python

在python,当我继承一个class。我到底继承了什么?我继承了 class 属性吗?如果是,那是否意味着我也继承了它们的默认值?最后,当我声明我要继承 class 时,我是否必须设置默认值,甚至在 sub-class 中提及属性?基本上,如果有的话,在 subclass 中重新声明属性有什么意义??

摘自the official documentation:

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.

以下示例应证明:

class A:
  foo = 0

class B(A):
  pass

# 'foo' isn't found in 'B' and the search proceeds in 'A'.
print(B.foo) # output: 0

如果在子类及其基类中定义了一个属性,则会创建第二个属性,该属性仅在子类中定义并在访问时优先。示例:

class A:
  foo = 1

class B(A):
  foo = 2

# 'A.foo' is a different object than 'B.foo'.
print(A.foo) # output: 1
print(B.foo) # output: 2