有什么替代方法来检查 python 中是否有任何属性吗?
a = SomeClass()
if hasattr(a, 'property'):
a.property
这是检查是否有财产的唯一方法吗?还有其他方法可以做同样的事情吗?
a = SomeClass()
if hasattr(a, 'property'):
a.property
Is this the only way to check if there is a property or not? Is there any other way to do the same thing?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以只使用该属性并捕获 AttributeError 异常(如果它不存在)。但使用
hasattr
也是一种合理的方法。捕获异常的一个潜在问题是,您无法轻松区分属性不存在和存在,但当您调用它时,某些代码会运行,并且该代码会引发
AttributeError< /code> (可能是由于代码中的错误)。
您可能还想查看这些相关问题以获取有关此主题的更多信息:
You could just use the property and catch the
AttributeError
exception if it doesn't exist. But usinghasattr
is also a reasonable approach.A potential issue with catching the exception is that you can't easily distinguish between the attribute not existing, and it existing but when you call it some code is run and that code raises an
AttributeError
(perhaps due to a bug in the code).You may also want to look at these related questions for more information on this topic:
好吧,您可以尝试访问它并捕获
AttributeError
,以防它不存在。Well, you can just try to access it and catch
AttributeError
in case it doesn't exist.您还可以使用:
You could also use:
也不优雅,但为了完整性,即使没有为对象定义
__dict__
,使用dir()
也可以工作:另请参阅
dir()
和__dict__< 之间最大的区别是什么/代码> 在Python
Not elegant either but for the sake of completeness using
dir()
also works even when__dict__
is not defined for the object:See also What's the biggest difference between
dir()
and__dict__
in Python