python面向对象继承练习

1. 建立一个汽车类Auto,包括轮胎个数,汽车颜色,车身重量,速度等属性,并通过不同的构造方法创建实例

至少要求 汽车能够加速 减速 停车。 再定义一个小汽车类CarAuto 继承Auto 并添加空调、CD属性,并且重新实现方法覆盖加速、减速的方法


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. 创建一个Person类,添加一个类字段用来统计Perosn类的对象的个数

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. 创建一个动物类,拥有属性:性别、年龄、颜色、类型 ,

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


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的对象:性别-%s 年龄-%d 颜色-%s 类型-%s/' % (self.__class__.__name__,self.gender,self.age,self.color,self.type)


dog1 = Animal('男', 2, '白色', '哈士奇')
print(dog1)

4. 写一个圆类, 拥有属性半径、面积和周长;要求获取面积和周长的时候的时候可以根据半径的值把对应的值取到。

但是给面积和周长赋值的时候,程序直接崩溃,并且提示改属性不能赋值


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

你可能感兴趣的:(python面向对象继承练习)