gpt4 book ai didi

python - 派生类属性

转载 作者:太空宇宙 更新时间:2023-11-03 14:10:33 25 4
gpt4 key购买 nike

Class A(): 
x=0

class B(A):
b=1

1-print(B.__dict__) # B.dict中没有 x 属性

if B.x==0:
B.x=1

2-print(B.__dict__) # B.dict中有x属性 为什么1和2的输出不同?

最佳答案

因为x属于A。请注意,B 可以访问 A 命名空间,因为它继承自 A,但这并不意味着这两个命名空间是等效的。 B 在第二个示例中具有 x 属性,因为您为 B 提供了 x 属性:即 B.x=1

熟悉 Python Data Model 非常重要。请注意,在“自定义类”下的标准类型层次结构中,有一些高度相关的信息:

Custom class types are typically created by class definitions (see section Class definitions). A class has a namespace implemented by a dictionary object. Class attribute references are translated to lookups in this dictionary, e.g., C.x is translated to C.__dict__["x"] (although there are a number of hooks which allow for other means of locating attributes). When the attribute name is not found there, the attribute search continues in the base classes. This search of the base classes uses the C3 method resolution order which behaves correctly even in the presence of ‘diamond’ inheritance structures where there are multiple inheritance paths leading back to a common ancestor. Additional details on the C3 MRO used by Python can be found in the documentation accompanying the 2.3 release at https://www.python.org/download/releases/2.3/mro/.

...

Class attribute assignments update the class’s dictionary, never the dictionary of a base class.

关于python - 派生类属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48531882/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com