怎么在使用前判断 Python 对象是否包含某个属性或者某个方法?
class FooClass:
pass
k = FooClass()
k.someAtt = 2
k.att
输出:
Traceback (most recent call last):
File "Untitled.py", line 6, in <module>
k.att
AttributeError: FooClass instance has no attribute 'att'
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
方法一:通过异常捕捉来实现逻辑
方法二:调用hasattr方法
hasattr(object, name)
说明:判断对象object是否包含名为name的特性(hasattr是通过调用getattr(ojbect, name)是否抛出异常来实现的)。
参数object:对象。
参数name:特性名称。
方法三:使用dir方法
另外, 这种问题可以使用google搜索下,善用google
dir(FooClass)
http://stackoverflow.com/questions/3681272/can-i-get-a-reference-to-a-python-property
http://stackoverflow.com/questions/191010/how-to-get-a-complete-list-of-objects-methods-and-attributes