建议用记事本写好再用用环境运行这样的效果好
1.(1)编写一个矩形类Rect,包含:矩形的宽width;矩形的高height。要求创建对象的时候必须给width和height传值
两个方法:求矩形面积的方法area(),求矩形周长的方法perimeter()
(2)通过继承Rect类编写一个具有确定位置的矩形类PlainRect,其确定位置用矩形的左上角座标来标识,包含:
添加两个属性:矩形左上角座标start_x和start_y。要求创建PlainRect对象的时候width和height必须赋值,start_x和start_y可以赋值可以不赋值。
添加一个方法:判断某个点是否在矩形内部的方法is_inside()。如在矩形内,返回True, 否则,返回False。
class Rect():
def __init__(self,width,heigth):
self.width = width
self.heigth = heigth
def area(self):
s = self.width * self.heigth
print(s)
def perimeter(self):
z = (self.width + self.heigth)*2
print(z)
class PlainRact(Ract):
def __init__(self,start_x,start_y,width,heigth)
self.start_x = start_x
self.start_y = start_y
#super().__init__(self,width,heigth)super方法调用
Ract.__init__(self,width,heigth)#通过父类名调用
def is_inside(self,x,y):
if x > 0 and x < self.start_x and y < 0 and y > -self.start_y:
print('在矩形内部')
return True
else:
print("不在矩形里面")
return False
if __name__ == '__main__':
a = PlainRact(100,100,50,20)
a.area()
a.is_inside(20,20)
2.定义一个Time类,对象属性包括:时、分、秒;通过init初始化属性。对象方法有: add_hour(self,num) 把小时加num add_minute(self,num) 把分钟加num add_second(self,num) 把秒数加num 定义show方法,打印格式化的时间字符串:“04:16:09”
class Time():
def __init__(self,hour,min,second):
self.hour = hour
self.min = min
self.second = second
def add_hour(self,num):
self.hour += num
def add_minute(self,num):
self.min += num
def add_second(self,num):
self.second += num
def show(self):
print("%02d:%02d:%02d"%(self.hour,self.min,self.second))
if __name__=="__main__":
t = Time(15,45,9)
t.add_hour(2)
t.show()
3.定义一个交通工具(Vehicle)的类其中有:
类属性最大速度max_speed = 120,对象属性:颜色(color),品牌(brand),速度(speed) 。
方法: 移动(move() 打印brand品牌color颜色的车开始移动啦!)
设置最大速度(setMaxSpeed(max_speed) 参数是最大速度)
加速speedUp(), 对象属性speed每次加10
减速speedDown(),对象属性speed每次减10
打印对象可以现实交通工具的详细信息
- 实例化一个交通工具对象并初始化speed,color,brand.
- 通过对象调用加速和减速,和移动方法
- 修改最大值速度是:150
- 打印对象显示详细信息
class Vehicle():
max_speed = 120
def __init__(self, color, brand, speed):
self.color = color
self.brand = brand
self.speed = speed
def move(self):
print("%s品牌%s的车开始移动了,速度为%d" % (self.brand, self.color, self.speed))
def speedUp(self):
self.speed += 10
def speedDown(self):
self.speed -= 10
if __name__ == '__main__':
p = Vehicle('red', '姐姐好', 50)
Vehicle.max_speed = 150
print(Vehicle.max_speed)
p.speedUp()
p.speedUp()
p.speedUp()
p.move()
print(p)