Key Word(s): Class methods, Static methods, Instance methods, Dunder methods
Exercise 1¶
Last lecture, you wrote a class to create circles from two points: the circle center and another point on the circle. Of course, someone might want to create a circle simply by providing the radius and no coordinate information. They should still be able to do all the same calculations as before (area and circumference).
You will provide this functionality by writing a subclass called Rcircle
of the superclass Circle
.
Requirements¶
- Must inherit from
Circle
- Must have it's own constructor. The constructor accepts the circle radius supplied by the user as its argument. That is
__init__(self, r)
. - The circle radius must be set in the constructor.
- The
Rcircle
subclass must reimplement theradius
function. It does not make sense forRcircle
to inherit theradius
method fromCircle
since an instance ofRcircle
doesn't know anything about the coordinates of the circle. - Include the
__eq__
special method to compare two circles.
Demo your class.
Bonus¶
Feel free to play with some of the other dunder methods. For example, it might be fun to add two circles (you get to define what that means!). Be careful with __add__
; you'll need to look into using __radd__
as well.
What other dunder methods would make sense?
Your Circle
class from last time should have looked something like the following. Of course, there are many, many ways to implement such a class. Feel free to keep your solution.
class Circle:
'''A class for circles
Constructor is initialized with two tuples, one for the center of the circle
and the other for a point on the circle.
Methods include radius, area, and circum. None of these methods accept any arguments.
The user is not required to pre-compute the radius of the circle. Exception testing is
done in area and circum to check for a circle radius. If it doesn't exist, a radius is
computed.
'''
def __init__(self, center, point):
self.xc = center[0]
self.yc = center[1]
self.x = point[0]
self.y = point[1]
def radius(self):
x = self.x - self.xc
y = self.y - self.yc
self.R = np.sqrt(x * x + y * y)
def area(self):
try:
self.A = np.pi * self.R* self.R
except AttributeError:
x = self.x - self.xc
y = self.y - self.yc
r = np.sqrt(x * x + y * y)
self.R = r
self.A = np.pi * r * r
def circum(self):
try:
self.C = 2.0 * np.pi * self.R
except AttributeError:
x = self.x - self.xc
y = self.y - self.yc
r = np.sqrt(x * x + y * y)
self.R = r
self.C = 2.0 * np.pi * r
Deliverables¶
Please submit your lecture exercise in a single file called LE71.py
. The same file should also demo the basic functionality.