如何检查类属性是在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热门推荐
10 孩子新年祝福语简短精辟
11 国庆中秋祝福语大全简短
12 对情侣朋友祝福语简短
13 生日祝福语对妈妈简短
14 节日祝福语大全简短创意
15 给长辈冬至祝福语 简短
16 成语祝福语精选大全简短
17 生日祝福语宿舍舍友 简短
18 旅游祝福语简短老师发言