Python编程作业中限制使用内置类方法的技术问询
Great question! When teaching Python and asking students to reimplement core built-in functionality (like your insert_sorted() and insertion_sort() task), enforcing restrictions on specific list methods is crucial to ensure they practice the intended logic rather than taking shortcuts. Here are practical, actionable approaches you can use:
1. Static Code Analysis with AST
Python's built-in ast module lets you parse student code into an abstract syntax tree, making it easy to detect calls to forbidden methods accurately (unlike regex, which can have false positives).
For example, you can write a small script to scan for calls to list.append(), list.insert(), list.sort(), or even the global sorted() function:
import ast FORBIDDEN_METHODS = {'append', 'insert', 'sort'} FORBIDDEN_FUNCTIONS = {'sorted'} def check_for_forbidden_code(code): tree = ast.parse(code) for node in ast.walk(tree): # Check for method calls like lst.append(...) if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute): if node.func.attr in FORBIDDEN_METHODS: return f"Forbidden method used: {node.func.attr}" # Check for function calls like sorted(...) if isinstance(node, ast.Call) and isinstance(node.func, ast.Name): if node.func.id in FORBIDDEN_FUNCTIONS: return f"Forbidden function used: {node.func.id}" return None
Run this script against each student's submission to flag potential violations. It’s ideal for batch processing, though it won’t catch extremely obfuscated code (like getattr(lst, 'append')(x)), which is rare in student work.
2. Provide a Restricted List Class
Create a custom list subclass that disables forbidden methods, then require students to use this class instead of the native list. This gives students immediate feedback if they accidentally use a restricted method.
Example implementation:
class RestrictedList(list): def append(self, *args, **kwargs): raise NotImplementedError("`append()` is not allowed for this assignment. Implement your own insertion logic.") def insert(self, *args, **kwargs): raise NotImplementedError("`insert()` is not allowed for this assignment. Use your `insert_sorted()` function instead.") def sort(self, *args, **kwargs): raise NotImplementedError("`sort()` is not allowed for this assignment. Implement your own `insertion_sort()` function.") # Add more methods to restrict if needed (e.g., extend, reverse)
In your assignment instructions, tell students to initialize their lists with my_list = RestrictedList() instead of my_list = []. If they try to call a forbidden method, the code will throw a clear error. To prevent workarounds (like converting to a native list), you can add checks in the subclass or scan their code for list(my_restricted_list) calls.
3. Combined Automated Checks + Manual Code Review
Automated tools handle the bulk of detection, but manual review adds a layer of accuracy for edge cases:
- Use the AST script to flag submissions with potential violations.
- For flagged submissions, do a quick manual check to confirm if it’s a true violation (e.g., a student defining their own
appendfunction isn’t a problem). - Ask students to add comments explaining their implementation logic—this helps you verify they’re writing the intended code, not just calling built-ins.
This approach balances efficiency and accuracy, especially for larger classes.
4. Validate Logic with Test Cases
Even if students find a way to bypass method restrictions, test cases can ensure they’ve mastered the core concept. Write unit tests that verify the behavior of insert_sorted() and insertion_sort():
- Test
insert_sorted()with unsorted inputs to confirm the list remains ordered after each insertion. - Test
insertion_sort()with different edge cases (empty list, single element, reverse-sorted list) to ensure it returns a correctly sorted new list.
For example:
import unittest from student_code import insert_sorted, insertion_sort class TestSortingAssignments(unittest.TestCase): def test_insert_sorted(self): lst = [] insert_sorted(lst, 3) self.assertEqual(lst, [3]) insert_sorted(lst, 1) self.assertEqual(lst, [1, 3]) insert_sorted(lst, 2) self.assertEqual(lst, [1, 2, 3]) def test_insertion_sort(self): self.assertEqual(insertion_sort([3,1,2]), [1,2,3]) self.assertEqual(insertion_sort([]), []) self.assertEqual(insertion_sort([5]), [5]) if __name__ == '__main__': unittest.main()
This ensures students aren’t just avoiding forbidden methods—they’re actually implementing the required logic correctly.
Bonus Tips
- Be Explicit in Instructions: Clearly list forbidden methods/functions in your assignment description (e.g., "Do NOT use
list.append(),list.insert(),list.sort(), orsorted()"). - Address Edge Cases: For advanced students who might try obfuscated workarounds, you can add checks in your restricted class or AST script to catch dynamic calls (like
eval("lst.append(5)")).
内容的提问来源于stack exchange,提问作者Aman

