Skip to main content
 首页 » 编程设计

python之限制使用内置类中的方法进行编程作业

2024年12月31日17yxwkf

我使用 Python 教授编码,在一些作业中,希望学生实现由内置函数或内置类的方法提供的功能。一个示例作业是我希望学生编写两个函数 - 一个称为 insert_sorted(),它向列表添加一个元素,以便列表保持排序,另一个称为 insertion_sort() 返回一个新列表并使用 insert_sorted() 进行排序。

我访问学生的代码是通过单元测试用例,我可以在单元测试用例中调用这些函数。问题是在insert_sorted()函数中,同学们可以使用list.sort()方法,而在insertion_sorted()函数中,他们可以使用 sorted() 内置函数。

覆盖内置函数很容易(在这种情况下会引发异常,并显示不允许使用它们的消息)。我还可以覆盖内置模块中的对象和函数(例如,我需要阻止使用 math.factorial() 函数)。但是我无法替换内置类型的方法,如下面的代码所示:

def error(): 
    raise Exception("Not allowed.") 
list.sort = error 

我得到错误:

Traceback (most recent call last): 
  File "main.py", line 3, in <module> 
    list.sort = error 
TypeError: can't set attributes of built-in/extension type 'list' 

有没有办法禁止在内置类中使用特定方法?

请您参考如下方法:

forbiddenfruit或许能帮到你:

This project aims to help you reach heaven while writing tests, but it may lead you to hell if used on production code.

It basically allows you to patch built-in objects, declared in C through python.

这是一个例子:

from forbiddenfruit import curse 
 
def broken_sort(self): 
    print("NOT DOING ANYTHING!") 
    return None 
 
curse(list, "sort", broken_sort) 
 
some_list = [3, 4, 5, 1, 2] 
some_list.sort() 
print(some_list) 

输出:

NOT DOING ANYTHING! 
[3, 4, 5, 1, 2] 

虽然它在我的系统上似乎不能可靠地工作,但它输出

[1, 2, 3, 4, 5] 

一半时间。这是由于race condition吗? ?我不知道。 :-/ 该项目可能值得进行一次小型调查。