1.建立一个汽车类Auto,包括轮胎个数,汽车颜色,车身重量,速度等属性,并通过不同的构造方法创建实例。
至少要求 汽车能够加速 减速 停车。
再定义一个小汽车类CarAuto 继承Auto 并添加空调、CD属性,并且重新实现方法覆盖加速、减速的方法
import math
class Auto:
a = 10
def __init__(self, color, weight, speed, num=4):
self.tires_num = num
self.color = color
self.weight = weight
self.speed = speed
def speed_up(self):
speed_u = self.speed + Auto.a
return speed_u
def speed_down(self):
speed_d = self.speed - self.a
return speed_d
@staticmethod
def stop():
return '停车'
class CarAuto(Auto):
a = 5
def __init__(self, color, weight, speed, num=4, air='空调', cd='CD'):
super().__init__(self, color, weight, speed)
self.air_conditioner = air
self.cd = cd
def speed_up(self):
speed_u = self.speed + Auto.a
return speed_u
def speed_down(self):
speed_d = self.speed - self.a
return speed_d
car1 = CarAuto('黑色', 120, 230)
print(car1.speed_down())
2.创建一个Person类,添加一个类字段用来统计Perosn类的对象的个数
class Person:
number = 0
def __init__(self, name):
self.name = name
Person.number += 1
p1 = Person('小明')
P2 = Person('小凤')
print(Person.number)
3.创建一个动物类,拥有属性:性别、年龄、颜色、类型 ,
要求打印这个类的对象的时候以'/XXX的对象: 性别-? 年龄-? 颜色-? 类型-?/' 的形式来打印
class Animal:
def __init__(self, age, color, class1, gender='公'):
self.gender = gender
self.age = age
self.color = color
self.a_class = class1
def __repr__(self):
return '/Animal的对象:' + '性别-%s 年龄-%d 颜色-%s 类型-%s' % (self.gender, self.age, self.color, self.a_class) + '/'
animal1 = Animal(2, '黑白', 'panda')
print(animal1)
4.写一个圆类, 拥有属性半径、面积和周长;要求获取面积和周长的时候可以根据半径的值把对应的值取到。
但是给面积和周长赋值的时候,程序直接崩溃,并且提示改属性不能赋值
class Error(Exception):
def __str__(self):
return '该属性不能赋值'
class Circle:
def __init__(self, radius):
self.radius = radius
self._area = 0
self._perimeter = 0
@property
def area(self):
return self.radius,(self.radius**2)*math.pi
@area.setter
def area(self,x):
if isinstance(x, int) or isinstance(x,float):
raise Error
self._area = x
@property
def perimeter(self):
return self.radius, self.radius * 2 * math.pi
@perimeter.setter
def perimeter(self,x):
if isinstance(x, int) or isinstance(x, float):
raise Error
self._perimeter = x
c1 = Circle(4)
c1.area = 1
print(c1.area)