from math import pi
"""
1.建立一个汽车类Auto,包括轮胎个数,汽车颜色,车身重量,速度等属性,
并通过不同的构造方法创建实例。至少要求 汽车能够加速 减速 停车。
再定义一个小汽车类CarAuto 继承Auto 并添加空调、CD属性,
并且重新实现方法覆盖加速、减速的方法
"""
class Auto:
def __init__(self, color='白色', weight=50, speed=0):
# color='红色', weight=100, speed=10
self.tyre_count = 4
self.color = color
self.weight = weight
self.speed = speed
self.__max_speed = 300
def speed_up(self, value):
"""加速"""
new_speed = self.speed + value
if new_speed > self.__max_speed:
self.speed = self.__max_speed
else:
self.speed = new_speed
def speed_down(self, value):
"""减速"""
new_speed = self.speed - value
if new_speed < 0:
self.speed = 0
else:
self.speed = new_speed
def stop(self):
"""停车"""
self.speed = 0
class CarAuto(Auto):
def __init__(self, color='', weight=100, speed=10):
# color='红色', weight=100, speed=10
super().__init__(color, weight, speed) # super().__init__('红色', 100, 10)
self.CD = ''
self.air_conditioner = '格力'
c1 = CarAuto('红色')
print(c1.__dict__)
"""
3.创建一个动物类,拥有属性:性别、年龄、颜色、类型 ,
要求打印这个类的对象的时候以'/XXX的对象: 性别-? 年龄-? 颜色-? 类型-?/' 的形式来打印
"""
print('===================第三题===================')
class Animal:
def init(self, gender='公', age=1, color='黑色', type='爬行'):
self.gender = gender
self.age = age
self.color = color
self.type = type
def __repr__(self):
return '/%s的对象: 性别-%s 年龄-%d 颜色-%s 类型-%s/' % \
(self.__class__.__name__, self.gender, self.age, self.color, self.type)
class Dog(Animal):
pass
an1 = Animal()
print(an1)
dog1 = Dog()
print(dog1)
"""
4.写一个圆类, 拥有属性半径、面积和周长;要求获取面积和周长的时候的时候可以根据半径的值把对应的值取到。
但是给面积和周长赋值的时候,程序直接崩溃,并且提示改属性不能赋值
"""
print('===================第三题===================')
class ReadOnlyError(Exception):
def str(self):
return 'Modify the read-only property'
class Circle:
def init(self, r):
self.r = r
self._perimeter = 0
self._area = 0
# perimeter
@property
def perimeter(self):
return self.r*pi*2
@perimeter.setter
def perimeter(self, value):
raise ReadOnlyError
# area
@property
def area(self):
return pi*self.r**2
@area.setter
def area(self, value):
raise ReadOnlyError
c1 = Circle(10)
print(c1.area, c1.perimeter)
c1.r = 3
print(c1.area, c1.perimeter)