Python 有三种判断 class 是否包含字段的方法

dir

1
2
3
4
5
6
7
8
9
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: wxnacy([email protected])

class User():
pass

fields = dir(User)
print('foo' in fields) # False

hasattr

1
2
3
4
5
6
7
8
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: wxnacy([email protected])

class User():
pass

print(hasattr(User, 'foo')) # False

该方法在 py2 中不建议使用,详情见一个危险的Python函数,不推荐使用

getattr

1
2
3
4
5
6
7
8
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: wxnacy([email protected])

class User():
pass

print(getattr(User, 'foo', None)) # None

这种方法是最安全的

03-17 00:18