在 python 中,当我继承一个类时。我到底继承了什么?我在继承类属性吗?如果是,那是否意味着我也继承了它们的默认值?最后,当我声明我正在继承一个类时,我是否必须设置一个默认值,甚至在子类中提及属性。基本上,如果有的话,在子类中重新声明属性有什么意义??
请您参考如下方法:
取自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
