day14作业

建立一个汽车类Auto,包括轮胎个数,汽车颜色,车身重量,速度等属性,并通过不同的构造方法创建实例。至少要求 汽车能够加速 减速 停车。 再定义一个小汽车类CarAuto 继承Auto 并添加空调、CD属性,并且重新实现方法覆盖加速、减速的方法

class Auto:
    wheels = 4
    def __init__(self,color,weight,speed=100):
        self.color = color
        self.weight = weight
        self.speed = speed


    def speedup(self,a,t):
        v = a*t + self.speed
        print('加速至%d' % v)

    def slowdown(self,a,t):
        v = self.speed - a*t
        print('减速至%d' % v)

    @staticmethod
    def stop():
        print('靠边停车')


class CarAuto(Auto):
    def __init__(self,color,weight,speed=100,airconditioner=True,cd=True):
        super().__init__(color,weight,speed)
        self.airconditioner = airconditioner
        self.cd = cd

    def speedup(self,v):
        print('加速至%d' % (self.speed + v))

    def slowdown(self,v):
        print('减速至%d' % (self.speed - v))

2.创建一个Person类,添加一个类字段用来统计Perosn类的对象的个数

class Person:
    count = 0
    def __init__(self):
        self.__class__.count += 1

    @classmethod
    def show_count(cls):
        print('当前类有%d个对象' % cls.count)

p1 = Person()
p2 = Person()
p3 = Person()
Person.show_count()

3.创建一个动物类,拥有属性:性别、年龄、颜色、类型 ,

要求打印这个类的对象的时候以'/XXX的对象: 性别-? 年龄-? 颜色-? 类型-?/' 的形式来打印

class Animal:
    def __init__(self,gender,age,color,type):
        self.gender = gender
        self.age = age
        self.color = color
        self.type = type

    def __str__(self):
        class_name = self.__class__.__name__
        return '%s的对象:性别-%s 年龄-%d 颜色-%s 类型-%s' % (class_name,self.gender,self.age,self.color,self.type)


a1 = Animal('雌',5,'white','哺乳动物')
print(a1)

4.写一个圆类, 拥有属性半径、面积和周长;要求获取面积和周长的时候的时候可以根据半径的值把对应的值取到。但是给面积和周长赋值的时候,程序直接崩溃,并且提示改属性不能赋值

from math import pi

class AssignmentError(Exception):
    def __str__(self):
        return '该属性不能赋值'


class Circle:
    def __init__(self,radius):
        self.radius = radius
        self._perimeter = None
        self._area = None

    @property
    def perimeter(self):
        self._perimeter = 2*pi*self.radius
        return self._perimeter

    @perimeter.setter
    def perimeter(self,x):
        if x != None:
            raise AssignmentError

    @property
    def area(self):
        self._area = pi * self.radius**2
        return self._area

    @area.setter
    def area(self, x):
        if x != None:
            raise AssignmentError

c1 = Circle(3)
print(c1.area)
c1.perimeter = 3

你可能感兴趣的:(day14作业)