- 建立一个汽车类Auto,包括轮胎个数,汽车颜色,车身重量,速度等属性,
并通过不同的构造方法创建实例。至少要求汽车能够加速 减速 停车。
再定义一个小汽车类CarAuto 继承Auto 并添加空调、CD属性,并且重新实现方法覆盖加速、减速的方法
class Auto:
def __init__(self, color, weight, tyre=4):
self._tyre = tyre
self.color = color
self._weight = weight
self._speed = 0
@property
def tyre(self):
return self._tyre
@property
def weight(self):
return self._weight
@property
def speed(self):
return self._speed
def quick(self):
if self._speed >= 130:
print('时速过快,不能加速')
else:
self._speed += 10
print('提速中,当前时速为:{}Km/h'.format(self._speed))
def moderate(self):
if self._speed < 10:
print('低速行驶!')
else:
self._speed -= 10
print('减速中,当前时速为:{}Km/h'.format(self._speed))
def stop(self):
print('开始减速停车'.center(40, '='))
while self._speed:
self.moderate()
print('车停下来了!')
auto1 = Auto('黑色', '10t', 6)
auto1.quick()
auto1.quick()
auto1.quick()
auto1.moderate()
auto1.stop()
class CarAuto(Auto):
def __init__(self, air_cond, cd, tyre, color, weight):
super().__init__(color, weight, tyre)
self.air_cond = air_cond
self.cd = cd
def quick(self):
if self._speed >= 125:
print('时速过快,不能加速')
else:
self._speed += 15
print('新提速方法,当前时速为:{}Km/h'.format(self._speed))
def moderate(self):
if self._speed < 15:
print('低速行驶!')
else:
self._speed -= 15
print('新减速方法,当前时速为:{}Km/h'.format(self._speed))
car1 = CarAuto('有空调', '有CD', 4, '红色', '8t')
car1.quick()
car1.quick()
car1.quick()
car1.moderate()
car1.stop()
- 创建一个Person类,添加一个类字段用来统计Person类的对象的个数
class Person:
total = 0
def __init__(self):
Person.total += 1
p1 = Person()
p2 = Person()
p3 = Person()
p4 = Person()
print('对象个数:{}'.format(Person.total))
- 创建一个动物类,拥有属性:性别、年龄、颜色、类型 ,
要求打印这个类的对象的时候以'/XXX的对象: 性别-? 年龄-? 颜色-? 类型-?/' 的形式来打印
class Animal:
def __init__(self, color, mold, gender=1, age=0):
self._gender = gender
self.age = age
self.color = color
self._mold = mold
@property
def gender(self):
if self._gender == 1:
return '公'
return '母'
@property
def mold(self):
return self._mold
def __repr__(self):
return '/%s的对象:性别-%s 年龄-%d 颜色-%s 类型-%s/' %\
(Animal.__name__, self.gender, self.age, self.color, self.mold)
dog1 = Animal('白色', '中华田园犬', 0, 2)
print(dog1)
- 写一个圆类, 拥有属性半径、面积和周长;
要求获取面积和周长的时候的时候可以根据半径的值把对应的值取到。
但是给面积和周长赋值的时候,程序直接崩溃,并且提示该属性不能赋值
class Circle:
pi = 3.1415
def __init__(self, radius: float):
self.radius = radius
self._area = 0
self._perimeter = 0
@property
def area(self):
return '%.2f' % (Circle.pi * self.radius**2)
@area.setter
def area(self, value):
print('该属性不能赋值')
raise ValueError
@property
def perimeter(self):
return '%.2f' % (2*Circle.pi*self.radius)
@perimeter.setter
def perimeter(self, value):
print('该属性不能赋值')
raise ValueError
c1 = Circle(2)
print(c1.area)
print(c1.perimeter)
c1.radius = 5
print(c1.area)
print(c1.perimeter)