python - 检查函数是否包含 pass

标签 python python-3.x class oop python-3.5

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

def doSomething(self, x):
    pass

现在,P的一些子类可能已经实现了这个方法,有些还没有。有什么方法可以检查 doSomething(x) 在运行时是否除了 pass 什么都不做(例如,如果它被实现,就执行它,如果没有,跳过它)?

最佳答案

除了在实例上调用 doMethod() 之外,这里不需要做任何。调用无操作方法的成本并不高,以至于检测子类何时实现覆盖将为您节省任何费用。

所以您的第一个选择是只调用方法,不要担心它是一个空方法。这就是 pass for 的作用,为您提供一个什么都不做的简单父类方法。

接下来,你声明

Parent class contains method doSomething(x)

你可以用它来检测你是否还有那个方法;绑定(bind)方法的底层函数将是同一个对象:

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 的函数。

关于python - 检查函数是否包含 pass,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52706667/

相关文章:

Python Pandas : creating a dataframe using a function for one of the fields

python - Listview 上的 Django 过滤器查询

python-3.x - 类型错误 : 'function' object is not subscriptable in tensorflow

javascript - TypeScript类继承构造函数混淆

java - Main 如何访问类?

c++ - 类实例的内存分配——应该使用继承来减少内存消耗吗?

python - 尝试从谷歌新闻页面 : enthought canopy 获取信息时出现 beautifulsoup 错误

Python比较整数与十六进制和二进制数

python - 向 Folium map 添加标题或文本

python - + 与 f-string 的字符串连接