import math단위 테스트 및 수업

토마스 보젠, 2020년 9월
이 연습은 3장을 보완합니다.
연습
1.
‘area()’ 함수는 ‘radius’ 인수를 받아 원의 면적을 계산합니다. 다음 조건에 대해 assert 문을 사용하여 세 가지 테스트를 작성합니다. 1. ’area(1)’이 ’float’을 반환하는지 확인합니다. 2. ’area(0)’이 0 값을 반환하는지 확인합니다. 3. area(5)가 대략 78.5와 같다고 가정합니다(힌트: math.isclose(..., abs_tol=0.1)).
def area(radius):
"""Calculate the area of a circle based on the given radius."""
return math.pi * radius**2# Your answer here.2.
EAFP(허가보다 용서를 구하는 것이 더 쉽다) 철학의 정신을 따릅니다. area() 함수의 코드를 수정하고 try/just 문을 추가하여 아래와 같이 문자열을 area()에 전달하여 발생하는 유형 오류를 포착합니다.
area("10")--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-4-28e1bc493b84> in <module> ----> 1 area('10') <ipython-input-2-13e66cca8177> in area(radius) 1 def area(radius): 2 """Calculate the area of a circle based on the given radius.""" ----> 3 return math.pi * radius ** 2 TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'int'
def area(radius):
"""Calculate the area of a circle based on the given radius."""
pass # Remove this line and add your answer here.3.
LBYL(Look Before You Dop) 철학의 정신을 바탕으로 합니다. area() 함수의 코드를 수정하고 조건부 if/else 문을 추가하여 사용자가 area() 함수에 숫자(int 또는 float)를 전달했는지 확인하세요. 다른 것을 전달하면 TypeError를 발생시킵니다.
def area(radius):
"""Calculate the area of a circle based on the given radius."""
pass # Remove this line and add your answer here.4.
이 연습에서는 ‘Circle’이라는 클래스를 만들어 보겠습니다. 다음과 같은 특성을 가져야 합니다. 1. ’radius’ 인수로 시작하고 이를 인스턴스 속성으로 저장해야 합니다. 2. 원의 면적을 계산하는 ‘area()’ 메서드를 사용하세요. 3. 원의 둘레를 계산하는 ‘circumference()’ 메서드를 사용하세요. 4. Python의 특수 메서드인 __str__() 메서드를 사용하고 클래스의 인스턴스를 print()할 때 화면에 출력되는 내용을 제어합니다(자세한 내용은 여기에서 알아보세요). print() 문은 f"A Circle with radius {self.radius}" 문자열을 인쇄해야 합니다.
귀하의 수업을 확인할 수 있도록 몇 가지 테스트를 제공했습니다.
class Circle:
"""A circle with a radius r."""
pass # Remove this line and add your answer here.assert Circle(3).radius == 3, "Test 1 failed."
assert math.isclose(Circle(3).area(), 28.3, abs_tol=0.1), "Test 2 failed."
assert math.isclose(Circle(3).circumference(), 18.8, abs_tol=0.1), "Test 3 failed."
assert Circle(3).__str__() == "A Circle with radius 3", "Test 4 failed."--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-8-5dbdbcaa4346> in <module> ----> 1 assert Circle(3).radius == 3, "Test 1 failed." 2 assert math.isclose(Circle(3).area(), 28.3, abs_tol=0.1), "Test 2 failed." 3 assert math.isclose(Circle(3).circumference(), 18.8, abs_tol=0.1), "Test 3 failed." 4 assert Circle(3).__str__() == "A Circle with radius 3", "Test 4 failed." TypeError: Circle() takes no arguments
5.
이제 위에서 만든 원 클래스를 상속하는 새 클래스 구를 만들어 보겠습니다. 다음과 같은 특성을 가져야 합니다.
- 인스턴스 속성으로 저장되는 단일 인수 ’radius’를 사용하여 ’Circle’과 정확히 동일하게 시작되어야 합니다.
- 구의 부피(\(\frac{4}{3}{\pi}{r^3}\))를 계산하는 ‘volume()’ 메서드를 사용하세요.
print(Sphere(1))를 호출하면f"A Sphere with Volume 4.19"문자열을 출력합니다(힌트: 이전 질문의__str__()메서드를 떠올려 보세요).
귀하의 수업을 확인할 수 있도록 몇 가지 테스트를 제공했습니다.
# Your answer here.assert Sphere(3).radius == 3, "Test 1 failed."
assert math.isclose(Sphere(3).area(), 28.3, abs_tol=0.1), "Test 2 failed."
assert math.isclose(Sphere(3).circumference(), 18.8, abs_tol=0.1), "Test 3 failed."
assert math.isclose(Sphere(3).volume(), 113.1, abs_tol=0.1), "Test 3 failed."
assert Sphere(1).__str__() == "A Sphere with volume 4.19", "Test 4 failed."--------------------------------------------------------------------------- NameError Traceback (most recent call last) <ipython-input-10-605d8a1c6bb6> in <module> ----> 1 assert Sphere(3).radius == 3, "Test 1 failed." 2 assert math.isclose(Sphere(3).area(), 28.3, abs_tol=0.1), "Test 2 failed." 3 assert math.isclose(Sphere(3).circumference(), 18.8, abs_tol=0.1), "Test 3 failed." 4 assert math.isclose(Sphere(3).volume(), 113.1, abs_tol=0.1), "Test 3 failed." 5 assert Sphere(1).__str__() == "A Sphere with volume 4.19", "Test 4 failed." NameError: name 'Sphere' is not defined
6.
‘Sphere’ 클래스 사용자가 ‘반지름’ 대신 ’원주’로 클래스를 인스턴스화하려는 경우가 많다고 상상해 보세요. 사용자가 이 작업을 수행할 수 있도록 from_circ()라는 클래스 메서드를 Sphere 클래스에 추가합니다. 메서드는 전달된 ’원주’에서 ’반경’을 계산한 다음 해당 ’반경’을 사용하여 ’Sphere’의 인스턴스를 만들어야 합니다.
수정된 클래스를 확인할 수 있도록 몇 가지 테스트를 제공했습니다.
# Your answer here.assert Sphere.from_circ(0).radius == 0, "Test 1 failed."
assert Sphere.from_circ(3 * math.pi).radius == 1.5, "Test 2 failed."
assert math.isclose(Sphere.from_circ(6).radius, 0.95, abs_tol=0.1), "Test 3 failed."
assert math.isclose(Sphere.from_circ(6).volume(), 3.65, abs_tol=0.1), "Test 4 failed."
assert Sphere.from_circ(6).__str__() == "A Sphere with volume 3.65", "Test 5 failed."--------------------------------------------------------------------------- NameError Traceback (most recent call last) <ipython-input-12-c64f2af0ae75> in <module> ----> 1 assert Sphere.from_circ(0).radius == 0, "Test 1 failed." 2 assert Sphere.from_circ(3 * math.pi).radius == 1.5, "Test 2 failed." 3 assert math.isclose(Sphere.from_circ(6).radius, 0.95, abs_tol=0.1), "Test 3 failed." 4 assert math.isclose(Sphere.from_circ(6).volume(), 3.65, abs_tol=0.1), "Test 4 failed." 5 assert Sphere.from_circ(6).__str__() == "A Sphere with volume 3.65", "Test 5 failed." NameError: name 'Sphere' is not defined
솔루션
1.
‘area()’ 함수는 ‘radius’ 인수를 받아 원의 면적을 계산합니다. 다음 조건에 대해 assert 문을 사용하여 세 가지 테스트를 작성합니다. 1. ’area(1)’이 ’float’을 반환하는지 확인합니다. 2. ’area(0)’이 0 값을 반환하는지 확인합니다. 3. area(5)가 대략 78.5와 같다고 가정합니다(힌트: math.isclose(..., abs_tol=0.1)).
def area(radius):
"""Calculate the area of a circle based on the given radius."""
return math.pi * radius**2assert isinstance(area(1), float), "Test 1 failed!"
assert area(0) == 0, "Test 2 failed!"
assert math.isclose(area(5), 78.5, abs_tol=0.1)2.
EAFP(허가보다 용서를 구하는 것이 더 쉽다) 철학의 정신을 따릅니다. area() 함수의 코드를 수정하고 try/just 문을 추가하여 아래와 같이 문자열을 area()에 전달하여 발생하는 유형 오류를 포착합니다.
area("10")--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-15-28e1bc493b84> in <module> ----> 1 area('10') <ipython-input-13-13e66cca8177> in area(radius) 1 def area(radius): 2 """Calculate the area of a circle based on the given radius.""" ----> 3 return math.pi * radius ** 2 TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'int'
def area(radius):
"""Calculate the area of a circle based on the given radius."""
try:
return math.pi * radius**2
except TypeError:
print(f"radius should be a number but you entered a {type(radius)}")
except:
print("Some other error occurred!")3.
LBYL(Look Before You Dop) 철학의 정신을 바탕으로 합니다. area() 함수의 코드를 수정하고 조건부 if/else 문을 추가하여 사용자가 area() 함수에 숫자(int 또는 float)를 전달했는지 확인하세요. 다른 것을 전달하면 TypeError를 발생시킵니다.
def area(radius):
"""Calculate the area of a circle based on the given radius."""
if isinstance(radius, (int, float)):
return math.pi * radius**2
else:
raise TypeError(f"radius should be a number but you entered a {type(radius)}")4.
이 연습에서는 circle이라는 클래스를 생성하기를 원합니다. 다음과 같은 특성을 가져야 합니다. 1. ‘radius’ 인수로 시작하고 이를 인스턴스 속성으로 저장해야 합니다. 2. 원의 면적을 계산하는 ‘area()’ 메서드를 사용하세요. 3. 원의 둘레를 계산하는 ‘circumference()’ 메서드를 사용하세요. 4. Python의 특수 메서드인 __str__() 메서드를 사용하고 클래스의 인스턴스를 print()할 때 화면에 출력되는 내용을 제어합니다(자세한 내용은 여기에서 알아보세요). print() 문은 f"A Circle with radius {self.radius}" 문자열을 인쇄해야 합니다.
귀하의 수업을 확인할 수 있도록 몇 가지 테스트를 제공했습니다.
class Circle:
"""A circle with a radius r."""
def __init__(self, radius):
self.radius = radius
def area(self):
"""Calculate the area of the circle."""
return math.pi * self.radius**2
def circumference(self):
"""Calculate the circumference of the circle."""
return 2.0 * math.pi * self.radius
def __str__(self):
return f"A Circle with radius {self.radius}"assert Circle(3).radius == 3, "Test 1 failed."
assert math.isclose(Circle(3).area(), 28.3, abs_tol=0.1), "Test 2 failed."
assert math.isclose(Circle(3).circumference(), 18.8, abs_tol=0.1), "Test 3 failed."
assert Circle(3).__str__() == "A Circle with radius 3", "Test 4 failed."5.
이제 위에서 만든 원 클래스를 상속하는 새 클래스 구를 만들어 보겠습니다. 다음과 같은 특성을 가져야 합니다.
- 인스턴스 속성으로 저장되는 단일 인수 ’radius’를 사용하여 ’Circle’과 정확히 동일하게 시작되어야 합니다.
- 구의 부피(\(\frac{4}{3}{\pi}{r^3}\))를 계산하는 ‘volume()’ 메서드를 사용하세요.
print(Sphere(1))를 호출하면f"A Sphere with Volume 4.19"문자열을 출력합니다(힌트: 이전 질문의__str__()메서드를 떠올려 보세요).
귀하의 수업을 확인할 수 있도록 몇 가지 테스트를 제공했습니다.
class Sphere(Circle):
"""A sphere with a radius r."""
def volume(self):
"""Calculate the volume of the sphere."""
return 4 / 3 * math.pi * self.radius**3
def __str__(self):
return f"A Sphere with volume {self.volume():.2f}"assert Sphere(3).radius == 3, "Test 1 failed."
assert math.isclose(Sphere(3).area(), 28.3, abs_tol=0.1), "Test 2 failed."
assert math.isclose(Sphere(3).circumference(), 18.8, abs_tol=0.1), "Test 3 failed."
assert math.isclose(Sphere(3).volume(), 113.1, abs_tol=0.1), "Test 3 failed."
assert Sphere(1).__str__() == "A Sphere with volume 4.19", "Test 4 failed."6.
‘Sphere’ 클래스 사용자가 ‘반지름’ 대신 ’원주’로 클래스를 인스턴스화하려는 경우가 많다고 상상해 보세요. 사용자가 이 작업을 수행할 수 있도록 from_circ()라는 클래스 메서드를 Sphere 클래스에 추가합니다. 메서드는 전달된 ’원주’에서 ’반경’을 계산한 다음 해당 ’반경’을 사용하여 ’Sphere’의 인스턴스를 만들어야 합니다.
수정된 클래스를 확인할 수 있도록 몇 가지 테스트를 제공했습니다.
class Sphere(Circle):
"""A sphere with a radius r."""
def volume(self):
"""Calculate the volume of the sphere."""
return 4 / 3 * math.pi * self.radius**3
@classmethod
def from_circ(cls, circumference):
"""Make an instance of Sphere from a circumference."""
radius = circumference / (2 * math.pi)
return cls(radius)
def __str__(self):
return f"A Sphere with volume {self.volume():.2f}"assert Sphere.from_circ(0).radius == 0, "Test 1 failed."
assert Sphere.from_circ(3 * math.pi).radius == 1.5, "Test 2 failed."
assert math.isclose(Sphere.from_circ(6).radius, 0.95, abs_tol=0.1), "Test 3 failed."
assert math.isclose(Sphere.from_circ(6).volume(), 3.65, abs_tol=0.1), "Test 4 failed."
assert Sphere.from_circ(6).__str__() == "A Sphere with volume 3.65", "Test 5 failed."