如何检查 Python 中给定类中的类属性是否已定义或派生?
pythonserver side programmingprogramming
以下代码显示属性 'foo' 是否已在类 A 和 B 中定义或派生。
示例
class A: foo = 1 class B(A): pass print A.__dict__ #我们看到属性 foo 位于类 A 的 __dict__ 中。因此 foo 在类 A 中定义。 print hasattr(A, 'foo') #我们看到类 A 具有该属性,但它已定义。 print B.__dict__ #我们看到属性 foo 不存在于 B 类的 __dict__ 中。因此 foo 未在 B 类中定义 print hasattr(B, 'foo') #我们看到 B 类具有该属性,但它是派生的
输出
{'__module__': '__main__', 'foo': 1, '__doc__': None}
True
{'__module__': '__main__', '__doc__': None}
True
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

