如何检查类属性是在给定的Python类中定义还是派生的?
下面的代码显示如何在A和B类中定义或派生属性“foo”。
示例
class A: foo = 1 class B(A): pass print A.__dict__ #We see that the attribute foo is there in __dict__ of class A. So foo is defined in class A. print hasattr(A, 'foo') #We see that class A has the attribute but it is defined. print B.__dict__ #We see that the attribute foo is not there in __dict__ of class B. So foo is not defined in class B print hasattr(B, 'foo') #We see that class B has the attribute but it is derived
输出
{'__module__': '__main__', 'foo': 1, '__doc__': None}
True
{'__module__': '__main__', '__doc__': None}
True
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C程序设计
C++
C#
MongoDB
MySQL
Javascript
PHP