day14-面向对象(作业)

1. 声明一个电脑类

属性:品牌、颜色、内存大小
方法:打游戏、写代码、看视频

a.创建电脑类的对象,然后通过对象点的方式获取、修改、添加和删除它的属性
b.通过attr相关方法去获取、修改、添加和删除它的属性

class Computer:


    def __init__(self, brand, color, rom):
        self.brand = brand
        self.color = color
        self.rom = rom
    def play_game(self):
        print('打游戏')
    def coding(self):
        print('写代码')
    def watch_video(self):
        print('看视频')

f1 = Computer("小胖", "black", "130g")
print(f1.__dict__)
print(f1.brand, f1.color, f1.rom)
print(f1.__getattribute__("brand"),
      f1.__getattribute__("color"),
      f1.__getattribute__("rom"))
print(getattr(f1, "brand", "属性错误"),
      getattr(f1, "color", "属性错误"),
      getattr(f1, "rom", "属性错误"))
f1.color = "red"
f1.addattr = "addattr"
print(f1.__dict__)

f1.__setattr__("color", "blue")
f1.__setattr__("addcolor", "blue")
print(f1.__dict__)
setattr(f1, "color", "red")
setattr(f1, "add", "addred")
print(f1.__dict__)
del f1.addattr
delattr(f1, "add")
f1.__delattr__("addcolor")
print(f1.__dict__)

2.声明一个人的类和狗的类:

狗的属性:名字、颜色、年龄
狗的 法:叫唤
人的属性:名字、 年龄、狗
人的方法:遛狗
a.创建人的对象名字叫小明,让他拥有一条狗 ,然后让小明去遛狗

class Person:

    def __init__(self,name,age ,dog):
        self.name = name
        self.age = age
        self.dog = dog

    def walk_dog(self):
        print("%s有一条%d岁的%s的狗,叫%s,%s正在遛它" \
              % (self.name, self.dog.age, self.dog.color, self.dog.name, self.name))


class Dog:


    def __init__(self, name, color, age):
        self.name = name
        self.color = color
        self.age = age



    def bark(self):
        print(self.name + "正在叫唤:嘤嘤嘤")


dog1 = Dog('旺财', '黄色', 2)
person1 = Person('小明', 18, dog1)
person1.walk_dog()
dog1.bark()

3.声明一个矩形类:

属性: 长、宽
方法:计算周长和面积
a.创建不同的矩形,并且打印其周长和面积

class Rectangle:
  

    def __init__(self, length = 0, width = 0):
        self.length = length
        self.width = width

    def perimeter(self):
        num = self.width * 2 + self.length * 2

        print("长宽为%.2f,%.2f的矩形的周长是%.2f"
              % (self.length, self.width, num))

    def area(self):
        num = self.length * self.width

        print("长宽为%.2f,%.2f的矩形的面积是%.2f" \
              % (self.length, self.width, num))
r1 = Rectangle(3, 4)
r2 = Rectangle(2, 3)
r1.perimeter()
r2.perimeter()
r1.area()
r2.area()

4.创建一个学生类:

属性:姓名,年龄,学号,成绩
方法:答到,展示学生信息
创建一个班级类: 属性:学生,班级名
方法:添加学生,删除学生,点名, 获取班级中所有学生的平均值, 获取班级中成绩最好的学生

夜深了,先睡觉

你可能感兴趣的:(day14-面向对象(作业))