python代码没有错误却无法运行的原因-Python Shell没有显示错误,但程序未运行

1586010002-jmsa.png

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值