I wrote this program to learn the basics of OOP. When I run this program from IDLE in the Python Shell it doesn't show any errors but also doesn't print anything... I'm not sure how to go about figuring out what my errors are.
Here's my code:
class Shapes(object):
def __init__(self, width, length):
object.__init__(self)
self.setWidth(width)
self.setLength(length)
def getWidth(self):
return self.width
def setWidth(self, width):
if (width <= 0):
width = 5
else:
width = self.width
def getLength(self):
return self.length
def setLength(self, length):
if (length <= 0):
length = 10
else:
length = self.length
class Rectangle(Shapes):
def __init__(self, area, perimeter):
Shapes.__init__(self, length, width)
def getArea(length, width):
return length * width
def getPerimeter(length, width):
return (length * 2) + (width * 2)
def getStats(self):
print("Area: {}".format(self.getArea()))
print("Perimeter: {}".format(self.getPerimeter()))
print("Length: {}".format(self.getLength()))
print("Width: {}".format(self.getWidth()))
def main():
print("Rectangle a: ")
a = Rectangle(5, 7)
print("Area: {}".format(a.area))
print("Perimeter: {}".format(a.perimeter))
print( " ")
print("Rectangle b: ")
b = Rectangle()
b.width = 10
b.height = 20
print(b.getStats())
Here's what the Shell is doing, if you want to look:
http://imgur.com/DxyUZyY
What am I doing wrong and how can I correct this?
解决方案
You never call the main function. Unlike in C, where main function would automatically execute, in python, you have to explicitly call it; main doesn't hold any special significance and is just another function in python.
So at the end of your code, write:
main()
Once you run that, you will see errors like @Eric pointed in his comments, and many more.
There are many things wrong with your current code, here is a list of a few of them:
object.__init__(self) doesn't do anything
self.setWidth(width) calls the method, but the setWidth method tries to set to a variable that hasn't been declared yet.
So this needs to be corrected to
def setWidth(self, width):
if (width <= 0):
width = 5
else:
width = width # and not self.width
The above is true for setLength as well.
Since you are using these methods to set and get values, you should look into using @property.
Shapes.__init__(self, length, width) is not the correct call.
You need to look into super
length, width are not defined here.