我有一个父类P和几个子类。父类包含的方法doSomething(x)仅定义为:

def doSomething(self, x):
    pass


现在,P的某些子类可能已经实现了此方法,而有些则没有。有什么方法可以在运行时检查doSomething(x)除了pass之外什么都不会做(例如,如果已实现,请执行,否则,跳过它)?

最佳答案

除了在实例上调用doMethod()之外,这里不需要执行任何其他操作。调用no-op方法并不昂贵,以至于检测子类何时实现了重写将为您节省任何费用。

因此,您的第一选择是仅调用方法,而不必担心它是一个空方法。这就是pass的用途,它为您提供了一个简单却不执行任何操作的父类方法。

接下来,你说


  父类包含方法doSomething(x)


您可以使用它来检测是否还有该方法。 bound方法的基础功能将是同一对象:

hook = instance.doSomething
if hook.__func__ is ParentClass.doSomething:
    # they didn't override the method, so nothing needs to be done.


同样,我不确定为什么有人会这样做,因为该测试不会仅仅使用instance.doSomething()为您节省任何费用。

接下来,始终仅由语句pass组成的函数将始终被编译为相同的字节码。它与return None相同的字节码。如果您必须知道函数是否为空,则比较字节码:

_RETURN_NONE = (lambda: None).__code__.co_code

def is_pass(f):
    return f.__code__.co_code == _RETURN_NONE


实际上,这可以应用于任何仅返回None且不执行其他任何操作的函数或方法。

演示:

>>> class P:
...     def doSomething(self, x):
...         pass
...
>>> class Child1(P):
...     def doSomething(self, x):
...         print("We are doing something with {!r}!".format(x))
...
>>> class Child2(P):
...     pass
...
>>> instance1 = Child1()
>>> instance2 = Child2()
>>> instance1.doSomething(42)
We are doing something with 42!
>>> instance2.doSomething(42)
>>> instance1.doSomething.__func__ is P.doSomething
False
>>> instance2.doSomething.__func__ is P.doSomething
True
>>> is_pass(instance1.doSomething)
False
>>> is_pass(instance2.doSomething)
True
>>> def unrelated_function():
...     return 42
...
>>> def another_unrelated_function():
...     pass
...
>>> is_pass(unrelated_function)
False
>>> is_pass(another_unrelated_function)
True


请注意is_pass()如何在使用pass的任何函数上工作。

09-07 10:09