- 建立一个汽车类Auto,包括轮胎个数,汽车颜色,车身重量,速度等属性,并通过不同的构造方法创建实例。
至少要求 汽车能够加速 减速 停车。
再定义一个小汽车类CarAuto 继承Auto 并添加空调、CD属性,并且重新实现方法覆盖加速、减速的方法
class Auto:
def __init__(self,weight,speed,color = 'Black'):
self.tyre = 4
self.weight = weight
self.speed = speed
self.color = color
self.max_speed = 200
def speed_up(self,mount):
if self.speed + mount >self.max_speed:
self.speed = self.max_speed
print(('当前已是最高车速:%d') % self.speed)
else:
self.speed +=mount
print('已加速:%d,当前车速:%d' %(mount,self.speed))
def speed_down(self,mount):
if self.speed - mount <0:
self.speed = 0
print('已停车,当前车速%d' %self.speed)
else:
self.speed -=mount
print(('已减速%d,当前车速%d') %(mount,self.speed))
class CarAuto(Auto):
def __init__(self,air_condition,CD,weight,speed):
self.air_condition = air_condition
self.CD = CD
super().__init__(weight,speed)
def speed_up(self,mount):
if self.speed + mount >180:
self.speed = 180
print(('当前已是最高车速:%d') % self.speed)
else:
self.speed +=mount
print('已加速:%d,当前车速:%d' %(mount,self.speed))
def speed_down(self,mount):
if self.speed - mount <0:
self.speed = 0
print('已停车,当前车速%d' %self.speed)
else:
self.speed -=mount
print(('已减速%d,当前车速%d') %(mount,self.speed))
- 创建一个Person类,添加一个类字段用来统计Perosn类的对象的个数
class Person:
count_num = 0
def __init__(self,name):
self.name = name
Person.count_num += 1
p1 = Person('maggie')
p2 = Person('phil')
p3 = Person('clair')
print(Person.count_num) # 3
- 创建一个动物类,拥有属性:性别、年龄、颜色、类型 ,
要求打印这个类的对象的时候以'/XXX的对象: 性别-? 年龄-? 颜色-? 类型-?/' 的形式来打印
class Animal:
def __init__(self,color,species,age=0,sex = 'female'):
self.color = color
self.species =species
self.age = age
self.sex = sex
def __repr__(self):
return '/%s的对象:%s/' % (self.__class__,str(self.__dict__)[1:-1])
a1 = Animal('white','cat')
print(a1.__repr__())
- 写一个圆类,拥有属性半径、面积和周长;要求获取面积和周长的时候的可以根据半径的值把对应的值取到。
但是给面积和周长赋值的时候,程序直接崩溃,并且提示改属性不能赋值
class brokeError(Exception):
def __str__(self):
return '属性不能赋值'
class Circle:
def __init__(self,radius,perimeter=0,area=0):
self.radius = radius
self.pi = 3.14
self._perimeter = perimeter
self._area = area
@ property
def perimeter(self):
return 2*self.radius*self.pi
@ property
def area(self):
return self.radius**2 * self.pi
@perimeter.setter
def perimeter(self,x = None):
if x != None:
raise brokeError
c1 = Circle(20)
print(c1.perimeter) # 125.60000000000001
c1.perimeter = 20 # __main__.brokeError: 属性不能赋值#