python中关键字pass的用法 [英] usage of keyword pass in python

查看:142
本文介绍了python中关键字pass的用法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

除了偶尔出现的例外情况,例如在这里,我没有看到关键字pass在Python中使用率很高:还有其他可以接受/可以的好的编程实践用例示例吗?

I have not seen the keyword pass used much in Python, except for the occasional exception, such as in here: Why is "except: pass" a bad programming practice? Are there any other example use-cases of pass which are acceptable/okay programming practice?

推荐答案

一种用途是定义一个具有名称但不执行任何操作的存根"类或方法.也许最常见的情况是定义自定义Exception类:

One use is to define a "stub" class or method that has a name but doesn't do anything. Maybe the most common case of this is to define a custom Exception class:

class MyCustomException(Exception):
    pass

现在,您可以引发并捕获这种类型的异常.该类只存在于引发和捕获中,不需要任何与之相关的行为.

Now you can raise and catch exceptions of this type. The class exists only to be raised and caught, and doesn't need any behavior associated with it.

以类似的方式,API可能包含不做任何事情"的功能,这些功能本应在子类中被覆盖:

In similar fashion, APIs may include "do-nothing" functions that are meant to be overridden in subclasses:

class SomeComplexAPI(object):
    # This method may be overridden in subclasses, but the base-class implementation is a no-op
    def someAPIHook(self):
        pass

如果您根本没有定义方法,则SomeComplexAPI().someAPIHook()会引发异常,因为该方法不存在.用pass定义它可以确保即使它没有任何作用也可以安全地调用它.

If you didn't define the method at all, SomeComplexAPI().someAPIHook() would raise an exception because the method doesn't exist. Defining it with pass makes sure you can safely call it even if it doesn't do anything.

这篇关于python中关键字pass的用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆