1. 建立一个汽车类Auto,包括轮胎个数,汽车颜色,车身重量,速度等属性,并通过不同的构造方法创建实例。
至少要求 汽车能够加速 减速 停车。 再定义一个小汽车类CarAuto 继承Auto 并添加空调、CD属性,并且重新实现方法覆盖加速、减速的方法
import math
class Auto:
wheels = 4
def __init__(self, color, weight, speed=0):
self.color = color
self.weight = weight
self.speed = speed
def speed_up(self):
for i in range(5):
print("正在加速,当前时速%dkm/s" % (self.speed + int(i)))
def speed_down(self):
for i in range(5):
print("正在减速,当前时速%dkm/s" % (self.speed - int(i)))
@staticmethod
def parking():
print('停车~~~~~~~~~~')
class CarAuto(Auto):
def __init__(self, color, weight, speed, air_condition, cd_player):
super().__init__(color, weight, speed)
self.air_condition = air_condition
self.cd_player = cd_player
def speed_up(self):
for i in range(5):
print("正在加速,当前时速%dkm/s" % (self.speed + 3*int(i)))
def speed_down(self):
for i in range(5):
print("正在减速,当前时速%dkm/s" % (self.speed - 3*int(i)))
car1 = CarAuto('黑色', '3T', 90, '空调', 'BOSE')
print(car1.__dict__)
car1.speed_up()
print('==============================================')
car1.speed_down()
car1.parking()
2. 创建一个Person类,添加一个类字段用来统计Perosn类的对象的个数
class Person:
num = 0
@classmethod
def count(cls):
cls.num += 1
return cls.num
p1 = Person()
print('建立的对象个数%d个' % p1.count())
p2 = Person()
print('建立的对象个数%d个' % p2.count())
3. 创建一个动物类,拥有属性:性别、年龄、颜色、类型 ,要求打印这个类的对象的时候以'/XXX的对象: 性别-? 年龄-? 颜色-? 类型-?/' 的形式来打印
class Animals:
def __init__(self, gender, age, color, type):
self.gender = gender
self.age = age
self.color = color
self.type = type
def print_animals(self):
print('性别-%s 年龄-%d 颜色-%s 类型-%s' % (self.gender, self.age, self.color, self.type))
animals1 = Animals('女', 3, 'black', '豹子')
animals1.print_animals()
4. 写一个圆类, 拥有属性半径、面积和周长;要求获取面积和周长的时候的时候可以根据半径的值
把对应的值取到。但是给面积和周长赋值的时候,程序直接崩溃,并且提示改属性不能赋值
class ReadError(Exception):
def __str__(self):
print('该数据不能修改!!!!!!')
class Circle:
def __init__(self, radius):
self.radius = radius
self._area = 0
self._perimeter = 0
@property
def area(self):
return math.pi*self.radius**2
@property
def perimeter(self):
return 2*math.pi*self.radius
@area.setter
def area(self, value):
raise ReadError
@perimeter.setter
def perimeter(self, value):
raise ReadError
c1 = Circle(6)
print(c1.area)
print(c1.perimeter)
c1.area = 1000
# print(c1.area) # 该数据不能修改!!!!!!