python 修改内置字符串函数

python modify builtin string functions

是否可以在 Python 中修改或 - 至少 - 拒绝执行内置函数?为了教育目的,我需要确保 strings split 不可用。

比如我想,if call

'a,b,c'.split(',')

抛出异常或返回输入的字符串。

我想强迫某人编写该函数的自己版本。可能吗?
提前致谢!

内置类型(在您的情况下为 str)和方法不能进行猴子修补,因为它们是在 C 中实现的(对于 cpython 实现)。

不过,你可以定义一个子类,重新定义方法:

>>> class Mystr(str):
...     def split(self, *args):
...             raise Exception("Split is not defined")
... 
>>> Mystr("test").split(",")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in split
Exception: Split is not defined