python isinstance vs hasattr vs try/except:什么更好?

python isinstance vs hasattr vs try/except: What is better?(python isinstance vs hasattr vs try/except:什么更好?)
本文介绍了python isinstance vs hasattr vs try/except:什么更好?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我试图找出不同方法之间的权衡,以确定是否使用对象 obj 可以执行操作 do_stuff().据我了解,有三种方法可以确定这是否可行:

I am trying to figure out the tradeoffs between different approaches of determining whether or not with object obj you can perform action do_stuff(). As I understand, there are three ways of determining if this is possible:

# Way 1
if isinstance(obj, Foo):
    obj.do_stuff()

# Way 2
if hasattr(obj, 'do_stuff'):
    obj.do_stuff()

# Way 3
try:
    obj.do_stuff()
except:
    print 'Do something else'

首选方法是什么(为什么)?

Which is the preferred method (and why)?

推荐答案

我相信最后一种方法通常是 Python 程序员首选的,因为 座右铭 在 Python 社区中教授:请求原谅比请求许可更容易"(EAFP).

I believe that the last method is generally preferred by Python coders because of a motto taught in the Python community: "Easier to ask for forgiveness than permission" (EAFP).

简而言之,座右铭的意思是避免在做某事之前检查您是否可以做某事.相反,只需运行该操作.如果失败,请适当处理.

In a nutshell, the motto means to avoid checking if you can do something before you do it. Instead, just run the operation. If it fails, handle it appropriately.

另外,第三种方法还有一个额外的好处,就是明确操作应该起作用.

Also, the third method has the added advantage of making it clear that the operation should work.

话虽如此,您确实应该避免使用像这样的纯 except.这样做将捕获任何/所有异常,甚至是不相关的异常.相反,最好专门捕获异常.

With that said, you really should avoid using a bare except like that. Doing so will capture any/all exceptions, even the unrelated ones. Instead, it is best to capture exceptions specifically.

在这里,您需要捕获 AttributeError:

Here, you will want to capture for an AttributeError:

try:
    obj.do_stuff()   # Try to invoke do_stuff
except AttributeError:
    print 'Do something else'  # If unsuccessful, do something else

这篇关于python isinstance vs hasattr vs try/except:什么更好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How do I make a list of all members in a discord server using discord.py?(如何使用 discord.py 列出不和谐服务器中的所有成员?)
how to change discord.py bot activity(如何更改 discord.py 机器人活动)
Issues with getting VoiceChannel.members and Guild.members to return a full list(让 VoiceChannel.members 和 Guild.members 返回完整列表的问题)
Add button components to a message (discord.py)(将按钮组件添加到消息(discord.py))
on_message() and @bot.command issue(on_message() 和@bot.command 问题)
How to edit a message in discord.py(如何在 discord.py 中编辑消息)