1. 建立一個(gè)汽車類Auto每窖,包括輪胎個(gè)數(shù)款违,汽車顏色单匣,車身重量,速度等屬性谈宛,并通過不同的構(gòu)造方法創(chuàng)建實(shí)例
至少要求 汽車能夠加速 減速 停車。 再定義一個(gè)小汽車類CarAuto 繼承Auto 并添加空調(diào)胎署、CD屬性吆录,并且重新實(shí)現(xiàn)方法覆蓋加速、減速的方法
class Auto:
def __init__(self, color, weight, speed=0, tire=4):
self.tire = tire
self.color = color
self.weight = weight
self.speed = speed
def add_speed(self, value):
self.speed += value
if self.speed >= 200:
self.speed = 200
def sub_speed(self, value):
self.speed -= value
if self.speed < 0:
self.speed = 0
def stop(self):
self.speed = 0
class CarAuto(Auto):
def __init__(self, color, weight, air_conditioner, speed=0, tire=4, cd=''):
super().__init__(color, weight, speed, tire)
self.cd = cd
self.air_conditioner = air_conditioner
def add_speed(self, value):
self.speed += value
if self.speed >= 300:
self.speed = 300
def sub_speed(self, value):
self.speed -= value
if self.speed < 0:
self.speed = 0
2. 創(chuàng)建一個(gè)Person類琼牧,添加一個(gè)類字段用來統(tǒng)計(jì)Perosn類的對(duì)象的個(gè)數(shù)
class Person:
numbers = 0
def __init__(self, name):
Person.numbers += 1
self.name = name
@classmethod
def number(cls):
return cls.numbers
p1 = Person('aaa')
p2 = Person('bbb')
print(Person.number())
3. 創(chuàng)建一個(gè)動(dòng)物類恢筝,擁有屬性:性別、年齡巨坊、顏色撬槽、類型 ,
要求打印這個(gè)類的對(duì)象的時(shí)候以'/XXX的對(duì)象: 性別-? 年齡-? 顏色-? 類型-?/' 的形式來打印
class Animal:
def __init__(self, gender='男', age=0, color='黃色', type='泰迪'):
self.gender = gender
self.age = age
self.color = color
self.type = type
def __repr__(self):
return '/%s的對(duì)象:性別-%s 年齡-%d 顏色-%s 類型-%s/' % (self.__class__.__name__,self.gender,self.age,self.color,self.type)
dog1 = Animal('男', 2, '白色', '哈士奇')
print(dog1)
4. 寫一個(gè)圓類趾撵, 擁有屬性半徑侄柔、面積和周長(zhǎng);要求獲取面積和周長(zhǎng)的時(shí)候的時(shí)候可以根據(jù)半徑的值把對(duì)應(yīng)的值取到占调。
但是給面積和周長(zhǎng)賦值的時(shí)候暂题,程序直接崩潰,并且提示改屬性不能賦值
class WriteError(Exception):
def __str__(self):
return '該屬性不能賦值'
class Circle:
pi = 3.1415926
def __init__(self, radius):
self.radius = radius
self._area = 0
self._perimeter = 0
@property
def area(self):
return self.radius**2*Circle.pi
@property
def perimeter(self):
return 2*self.radius*Circle.pi
@area.setter
def area(self, value):
raise WriteError
@perimeter.setter
def perimeter(self, value):
raise WriteError
c1 = Circle(10)
print(c1.area)
c1.area = 100