Reputation: 3
SO I need to find the area of the rectangle. I must put a method in the Rectangle class called "CalcArea()" that multiplies the width * height. I have no clue how to do this and I'm so lost the book doesn't explain how to do this at all. Here's my code:
class Point():
x = 0.0
y = 0.0
def __init__(self, x, y):
self.x = x
self.y = y
print("Point Constructor")
def ToString(self):
return "{X:" + str(self.x) + ",Y:" + str(self.y) + "}"
class Ellipse(Point):
radiusV = 0.0
radiusH = 0.0
def __init__(self, x, y, radiusV, radiusH):
super().__init__(x,y)
self.radiusV = radiusV
self.radiusH = radiusH
print("Ellipse Constructor")
def ToString(self):
return super().ToString() + \
",{Radius: Vertical = " + str(self.radiusV) + ", Radius: Horizontal = " + str(self.radiusH) + "}"
p = Point(50,50)
print(p.ToString())
e = Ellipse(80,80,60,80)
print(e.ToString())
class Size():
width = 0.0
height = 0.0
def __init__(self, width, height):
self.width = width
self.height = height
print ("Size Constructor")
def ToString(self):
return "{Width = " + str(self.width) + \
", Height = " + str(self.height) + "}"
class Rectangle(Point, Size):
area = 0.0
def __init__(self, x, y, width, height):
Point.__init__(self,x,y)
Size.__init__(self,width,height)
print("Rectangle Constructor")
def ToString(self):
return Point.ToString(self) + "," + Size.ToString(self) +
s = Size (80,70)
print(s.ToString())
r = Rectangle(200,250,40,50)
print(r.ToString())
Upvotes: 0
Views: 219
Reputation: 2139
In your Rectangle
class use the following method
def calcArea(self):
return self.width * self.height
To print the area simply call
print mRectangle.calcArea()
where mRectangle
is an instance of the Rectangle
class.
self.width
and self.height
are available to you since Rectangle
inherits from Size
class and Size
has the instance variables width
and height
set appropriately in its constructor. These values are available to you since Rectangle
is a subclass of Size
.
Also your width = 0
and height = 0
in Size class might not be doing exactly what you think. They are static or class variables in Python and completely different from self.width
and self.height
Here is an example to illustrate that
>>> class MyClass():
... a = 0
... def __init__(self):
... self.a = 5
... def echo(self):
... print MyClass.a, self.a
...
>>> instance = MyClass()
>>> instance.echo()
0 5
>>> instance.a
5
>>> MyClass.a
0
>>>
In python you access class or static variables with the syntax ClassName.Variable
and can be accessed without creating an object of that class. Where as an instance variable can be called only with an instance of the class.
Upvotes: 2