gpt4 book ai didi

python只获取类属性没有父类(super class)

转载 作者:太空狗 更新时间:2023-10-30 02:34:38 25 4
gpt4 key购买 nike

那么是否有可能只为最具体的类获取属性的字典/列表?到目前为止我正在使用

   for attr, value in obj.__class__.__dict__.iteritems():

但这也会给我父类(super class)中定义的属性。有什么办法可以避免这种情况吗?

最佳答案

摘自 python documentation

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 for new-style classes in particular 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

换句话说,__dict__ 只包含类的“本地”属性,父类(super class)的属性存储在父类(super class) __dict__ 中。

因此,您可以使用 __class__.__dict__.iteritems() 仅检索类属性。

在 Python 3 上你应该使用 __class__.__dict__.items()

关于python只获取类属性没有父类(super class),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7241528/

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