Jupyter Notebook을 사용하여 Python 배우기
Jupyter, PyHamcrest 및 이들을 함께 묶는 작은 테스트 코드를 사용하면 단위 테스트에 적합한 Python 콘텐츠를 가르칠 수 있습니다.
Python 비디오 튜토리얼 칼럼에서 자세히 소개합니다~
Ruby 커뮤니티에 관한 몇 가지 예는 항상 저에게 깊은 인상을 주었습니다. 두 가지 예는 테스트에 대한 헌신과 시작의 용이성에 대한 강조입니다. . 둘 다의 가장 좋은 예는 테스트를 수정하여 Ruby를 배울 수 있는 Ruby Koans입니다.
이러한 놀라운 도구를 Python에 도입할 수만 있다면 더 나은 결과를 얻을 수 있을 것입니다. 예, Jupyter Notebook, PyHamcrest 및 약간의 테이프 같은 접착 코드를 사용하여 지침, 작업 코드 및 수정이 필요한 코드가 포함된 튜토리얼을 만들 수 있습니다.
먼저 "테이프"가 필요합니다. 일반적으로 pytest나 Virity와 같은 멋진 명령줄 테스터를 사용하여 테스트를 수행합니다. 종종 직접 실행하지도 않습니다. tox 또는 nox와 같은 도구를 사용하여 실행합니다. 그러나 Jupyter를 사용하면 테스트를 직접 실행할 수 있는 작은 글루 코드 조각을 작성해야 합니다.
다행히 이 코드는 짧고 간단합니다.
import unittest def run_test(klass): suite = unittest.TestLoader().loadTestsFromTestCase(klass) unittest.TextTestRunner(verbosity=2).run(suite) return klass复制代码
이제 첫 번째 연습 세션을 위한 장비가 준비되었습니다.
가르칠 때는 항상 간단한 연습부터 시작하여 자신감을 키우는 것이 좋습니다.
그래서 아주 간단한 테스트를 수정해 보겠습니다.
@run_test class TestNumbers(unittest.TestCase): def test_equality(self): expected_value = 3 # 只改这一行 self.assertEqual(1+1, expected_value)复制代码
test_equality (__main__.TestNumbers) ... FAIL ====================================================================== FAIL: test_equality (__main__.TestNumbers) ---------------------------------------------------------------------- Traceback (most recent call last): File "<ipython-input-7-5ebe25bc00f3>", line 6, in test_equality self.assertEqual(1+1, expected_value) AssertionError: 2 != 3 ---------------------------------------------------------------------- Ran 1 test in 0.002s FAILED (failures=1)复制代码
"Change just this line"은 학생들에게 유용한 표기법입니다. 수정해야 할 내용을 정확하게 나타냅니다. 그렇지 않으면 학생들은 첫 번째 줄을 return
으로 변경하여 테스트를 수정할 수 있습니다. return
来修复测试。
在这种情况下,修复很容易:
@run_test class TestNumbers(unittest.TestCase): def test_equality(self): expected_value = 2 # 修复后的代码行 self.assertEqual(1+1, expected_value)复制代码
test_equality (__main__.TestNumbers) ... ok ---------------------------------------------------------------------- Ran 1 test in 0.002s OK复制代码
然而,很快,unittest
库的原生断言将被证明是不够的。在 pytest
中,通过重写 assert
中的字节码来解决这个问题,使其具有神奇的属性和各种启发式方法。但这在 Jupyter notebook 中就不容易实现了。是时候挖出一个好的断言库了:PyHamcrest。
from hamcrest import * @run_test class TestList(unittest.TestCase): def test_equality(self): things = [1, 5, # 只改这一行 3] assert_that(things, has_items(1, 2, 3))复制代码
test_equality (__main__.TestList) ... FAIL ====================================================================== FAIL: test_equality (__main__.TestList) ---------------------------------------------------------------------- Traceback (most recent call last): File "<ipython-input-11-96c91225ee7d>", line 8, in test_equality assert_that(things, has_items(1, 2, 3)) AssertionError: Expected: (a sequence containing <1> and a sequence containing <2> and a sequence containing <3>) but: a sequence containing <2> was <[1, 5, 3]> ---------------------------------------------------------------------- Ran 1 test in 0.004s FAILED (failures=1)复制代码
PyHamcrest 不仅擅长灵活的断言,它还擅长清晰的错误信息。正因为如此,问题就显而易见了。[1, 5, 3]
不包含 2
,而且看起来很丑:
@run_test class TestList(unittest.TestCase): def test_equality(self): things = [1, 2, # 改完的行 3] assert_that(things, has_items(1, 2, 3))复制代码
test_equality (__main__.TestList) ... ok ---------------------------------------------------------------------- Ran 1 test in 0.001s OK复制代码
使用 Jupyter、PyHamcrest 和一点测试的粘合代码,你可以教授任何适用于单元测试的 Python 主题。
例如,下面可以帮助展示 Python 从字符串中去掉空白的不同方法之间的差异。
source_string = " hello world " @run_test class TestList(unittest.TestCase): # 这是个赠品:它可以工作! def test_complete_strip(self): result = source_string.strip() assert_that(result, all_of(starts_with("hello"), ends_with("world"))) def test_start_strip(self): result = source_string # 只改这一行 assert_that(result, all_of(starts_with("hello"), ends_with("world "))) def test_end_strip(self): result = source_string # 只改这一行 assert_that(result, all_of(starts_with(" hello"), ends_with("world")))复制代码
test_complete_strip (__main__.TestList) ... ok test_end_strip (__main__.TestList) ... FAIL test_start_strip (__main__.TestList) ... FAIL ====================================================================== FAIL: test_end_strip (__main__.TestList) ---------------------------------------------------------------------- Traceback (most recent call last): File "<ipython-input-16-3db7465bd5bf>", line 19, in test_end_strip assert_that(result, AssertionError: Expected: (a string starting with ' hello' and a string ending with 'world') but: a string ending with 'world' was ' hello world ' ====================================================================== FAIL: test_start_strip (__main__.TestList) ---------------------------------------------------------------------- Traceback (most recent call last): File "<ipython-input-16-3db7465bd5bf>", line 14, in test_start_strip assert_that(result, AssertionError: Expected: (a string starting with 'hello' and a string ending with 'world ') but: a string starting with 'hello' was ' hello world ' ---------------------------------------------------------------------- Ran 3 tests in 0.006s FAILED (failures=2)复制代码
理想情况下,学生们会意识到 .lstrip()
和 .rstrip()
这两个方法可以满足他们的需要。但如果他们不这样做,而是试图到处使用 .strip()
source_string = " hello world " @run_test class TestList(unittest.TestCase): # 这是个赠品:它可以工作! def test_complete_strip(self): result = source_string.strip() assert_that(result, all_of(starts_with("hello"), ends_with("world"))) def test_start_strip(self): result = source_string.strip() # 改完的行 assert_that(result, all_of(starts_with("hello"), ends_with("world "))) def test_end_strip(self): result = source_string.strip() # 改完的行 assert_that(result, all_of(starts_with(" hello"), ends_with("world")))复制代码
test_complete_strip (__main__.TestList) ... ok test_end_strip (__main__.TestList) ... FAIL test_start_strip (__main__.TestList) ... FAIL ====================================================================== FAIL: test_end_strip (__main__.TestList) ---------------------------------------------------------------------- Traceback (most recent call last): File "<ipython-input-17-6f9cfa1a997f>", line 19, in test_end_strip assert_that(result, AssertionError: Expected: (a string starting with ' hello' and a string ending with 'world') but: a string starting with ' hello' was 'hello world' ====================================================================== FAIL: test_start_strip (__main__.TestList) ---------------------------------------------------------------------- Traceback (most recent call last): File "<ipython-input-17-6f9cfa1a997f>", line 14, in test_start_strip assert_that(result, AssertionError: Expected: (a string starting with 'hello' and a string ending with 'world ') but: a string ending with 'world ' was 'hello world' ---------------------------------------------------------------------- Ran 3 tests in 0.007s FAILED (failures=2)复制代码
unittest
라이브러리의 기본 어설션이 불충분하다는 것이 증명될 것입니다. pytest
에서는 마법 속성과 다양한 경험적 방법을 갖도록 assert
의 바이트코드를 다시 작성하여 이 문제를 해결합니다. 하지만 Jupyter Notebook에서는 이를 달성하기가 쉽지 않습니다. 이제 좋은 주장 라이브러리인 PyHamcrest를 알아볼 시간입니다. source_string = " hello world " @run_test class TestList(unittest.TestCase): # 这是个赠品:它可以工作! def test_complete_strip(self): result = source_string.strip() assert_that(result, all_of(starts_with("hello"), ends_with("world"))) def test_start_strip(self): result = source_string.lstrip() # Fixed this line assert_that(result, all_of(starts_with("hello"), ends_with("world "))) def test_end_strip(self): result = source_string.rstrip() # Fixed this line assert_that(result, all_of(starts_with(" hello"), ends_with("world")))复制代码
test_complete_strip (__main__.TestList) ... ok test_end_strip (__main__.TestList) ... ok test_start_strip (__main__.TestList) ... ok ---------------------------------------------------------------------- Ran 3 tests in 0.005s OK复制代码
[1, 5, 3]
에는 2
가 포함되어 있지 않으며 보기에도 좋지 않습니다. rrreeerrreee
Jupyter, PyHamcrest를 사용한 글루 코드와 약간의 테스트를 사용하면 모든 Python 테마를 가르칠 수 있습니다. 단위 테스트용.지금 지식을 공유하세요! 🎜🎜🎜🎜 관련 무료 학습 추천: 🎜🎜🎜python 비디오 튜토리얼🎜🎜🎜🎜예를 들어, 다음은 문자열에서 공백을 제거하는 Python의 다양한 방법 간의 차이점을 보여주는 데 도움이 됩니다. rrreeerrreee이상적으로는 학생들이
.lstrip()
및.rstrip()
이 자신의 요구 사항을 충족한다는 것을 깨닫게 됩니다. 하지만 그렇게 하지 않고 대신.strip()
을 모든 곳에서 사용하려고 하면 rrreeerrreee 너무 많은 공백이 제거되었음을 보여주는 다른 오류 메시지가 표시됩니다. In a에서 rrreeerrreee 더 현실적인 튜토리얼이 있으면 더 많은 예시와 설명이 나올 것입니다. Jupyter Notebook을 사용하는 이 기술은 일부 예에 사용될 수 있으며 일부 예는 수정이 필요합니다. 실시간 교육, 비디오 수업 및 기타 분산된 목적으로 사용할 수 있으므로 학생들이 튜토리얼을 완료할 수 있습니다. 그들 자신.
위 내용은 Jupyter Notebook을 사용하여 Python 배우기의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제











Linux 터미널에서 Python 버전을 보려고 할 때 Linux 터미널에서 Python 버전을 볼 때 권한 문제에 대한 솔루션 ... Python을 입력하십시오 ...

10 시간 이내에 컴퓨터 초보자 프로그래밍 기본 사항을 가르치는 방법은 무엇입니까? 컴퓨터 초보자에게 프로그래밍 지식을 가르치는 데 10 시간 밖에 걸리지 않는다면 무엇을 가르치기로 선택 하시겠습니까?

Python의 Pandas 라이브러리를 사용할 때는 구조가 다른 두 데이터 프레임 사이에서 전체 열을 복사하는 방법이 일반적인 문제입니다. 두 개의 dats가 있다고 가정 해

Fiddlerevery Where를 사용할 때 Man-in-the-Middle Reading에 Fiddlereverywhere를 사용할 때 감지되는 방법 ...

Uvicorn은 HTTP 요청을 어떻게 지속적으로 듣습니까? Uvicorn은 ASGI를 기반으로 한 가벼운 웹 서버입니다. 핵심 기능 중 하나는 HTTP 요청을 듣고 진행하는 것입니다 ...

파이썬에서 문자열을 통해 객체를 동적으로 생성하고 메소드를 호출하는 방법은 무엇입니까? 특히 구성 또는 실행 해야하는 경우 일반적인 프로그래밍 요구 사항입니다.

Linux 터미널에서 Python 사용 ...
