Python——第六次作业
使用面向对象实现一个栈:
class Stack:
def __init__(self):
self.item = []
def push(self,item):
self.item.append(item)
def pop(self):
return self.item.pop()
def isEmpty(self):
if self.item == []:
return True
else:
return False
def size(self):
return len(self.item)
使用面向对象实现一个队列:
class Queue:
def __init__(self):
self.item = []
def push(self,item):
self.item.append(item)
def pop(self):
return self.item.pop(0)
def isEmpty(self):
if self.item == []:
return True
else:
return False
def size(self):
return len(self.item)
对于队列和栈的实现,方法大致相同,区别在于出栈/队列时的元素不同。
定义一个矩形类,求矩形的面积和周长:
class rectangle:
length = 0
wide = 0
perimeter = 0
area = 0
def __init__(self):
pass
def Cal(self):
self.perimeter = 2 * (self.length + self.wide)
self.area = self.length * self.wide
def setEdge(self):
self.length = float(input("请输入矩形的长:"))
self.wide = float(input("请输入矩形的宽:"))
print("输入成功!")
def printMess(self):
print("矩形周长为:%.2f"%self.perimeter)
print("矩形面积为:%.2f"%self.area)
if __name__ == '__main__':
r = rectangle()
r.setEdge()
r.Cal()
r.printMess()
定义一个三角形,求三角形的面积和周长(属性是:三边):
class triangle:
a = 0
b = 0
c = 0
area = 0
primeter = 0
def __init__(self):
pass
def Cal(self):
self.primeter = self.a + self.b + self.c
p = (a + b + c) / 2
self.area = pow(p * (p - a) * (p - b) * (p - c),0.5)
def setEdge(self):
self.a = float(input("请输入第一条边:"))
self.b = float(input("请输入第二条边:"))
self.c = float(input("请输入第三条边:"))
def printResult(self):
print("三角形的周长为:%.2f"%self.primeter)
print("三角形的面积为:%.2f"%self.area)
if __name__ == '__main__':
t = triangle()
t.setEdge()
t.Cal()
t.printResult()