forked from OSUrobotics/IntroPythonProgramming
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathb_practice_classes.py
More file actions
54 lines (43 loc) · 1.57 KB
/
b_practice_classes.py
File metadata and controls
54 lines (43 loc) · 1.57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#!/usr/bin/env python3
import numpy as np
#------------------------ Circle class ----------------------
# Create a class named Circle that takes as input a radius when it is created, and has two methods, one that
# returns the area of the circle, the other that returns the perimeter. Write code to create two circles, one with
# radius 1 and one with radius 2 and print out their area and circumference
#
# [optional-fancy] If you stick the two class instances in a list, you can print them both out with a for loop...
# ----------------- Answers --------------------------------
class Circle:
"""
A 2d circle.
"""
def __init__(self, radius):
"""
Constructor.
:param radius: The circle radius.
"""
# We're not going to allow a negative radius.
if radius < 0:
raise ValueError('Circle: Radius must be non-negative')
self.radius = radius
def __str__(self):
return 'Circle({0})'.format(self.radius)
def area(self):
"""
Circle radius.
:return: The radius of the circle.
"""
return np.pi * self.radius ** 2
def circumference(self):
"""
The circumference of the circle.
:return: The circle circumference.
"""
return 2 * np.pi * self.radius
if __name__ == '__main__':
c1 = Circle(1.0)
c2 = Circle(2.0)
# Since the circles are just... objects, we can stick them in a list
shapes = [c1, c2]
for s in shapes:
print(f"{s}: area is {s.area():0.2f}, circumference is {s.circumference():0.2f}")