检查类是否定义了函数的最快方法是什么?

2024-05-12 13:27:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在写一个人工智能状态空间搜索算法,我有一个通用类,可以用来快速实现一个搜索算法。子类将定义必要的操作,而算法则完成其余的操作。

这里是我陷入困境的地方:我想避免一次又一次地重新生成父状态,所以我有以下函数,它返回可以合法应用于任何状态的操作:

def get_operations(self, include_parent=True):
    ops = self._get_operations()
    if not include_parent and self.path.parent_op:
        try:
            parent_inverse = self.invert_op(self.path.parent_op)
            ops.remove(parent_inverse)
        except NotImplementedError:
            pass
    return ops

默认情况下,invert_op函数抛出。

有没有比捕获异常更快的方法来检查是否未定义函数?

我在考虑在dir中检查present,但这似乎不对。hasattr是通过调用getattr并检查它是否引发来实现的,这不是我想要的。


Tags: path函数selfgetinclude状态空间人工智能
3条回答

它在Python 2和Python 3中都可以工作

hasattr(connection, 'invert_opt')

如果连接对象定义了函数invert_opt,则hasattr返回True。这是给你的文件

https://docs.python.org/2/library/functions.html#hasattrhttps://docs.python.org/3/library/functions.html#hasattr

是的,使用getattr()获取属性,使用callable()验证它是一个方法:

invert_op = getattr(self, "invert_op", None)
if callable(invert_op):
    invert_op(self.path.parent_op)

注意,getattr()通常在属性不存在时抛出异常。但是,如果指定默认值(None,在本例中),它将返回该值。

Is there a faster way to check to see if the function is not defined than catching an exception?

你为什么反对?在大多数的Python案例中,请求宽恕总比允许好。;-)

hasattr is implemented by calling getattr and checking if it raises, which is not what I want.

再说一遍,为什么?以下是相当的Python:

    try:
        invert_op = self.invert_op
    except AttributeError:
        pass
    else:
        parent_inverse = invert_op(self.path.parent_op)
        ops.remove(parent_inverse)

或者

    # if you supply the optional `default` parameter, no exception is thrown
    invert_op = getattr(self, 'invert_op', None)  
    if invert_op is not None:
        parent_inverse = invert_op(self.path.parent_op)
        ops.remove(parent_inverse)

不过,请注意,getattr(obj, attr, default)基本上也是通过捕获异常来实现的。在Python land没有什么不对的!

相关问题 更多 >