8.8Day014 面向对象基础

1.声明⼀个电脑类: 属性:品牌、颜色、内存大小 方法:打游戏、写代码、看视频

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

b.通过attr相关⽅方法去获取、修改、添加和删除它的属性

class Computer:
    def __init__(self, brand, color, internal):
        self.brand = brand
        self.color = color
        self.internal = internal

    def play_game(self):
        print('%s:用来打游戏' % self.brand)

    def write_code(self):
        print('%s:用来写代码' % self.brand)

    def watch_tv(self):
        print('%s:用来看视频' % self.brand)


computer1 = Computer('联想', 'black', 8)
computer2 = Computer('戴尔', 'white', 6)
print(computer1.color)
computer1.name = '华硕'
print(computer1.brand)
del computer1.internal
# print(computer1.internal)   # AttributeError: 'Computer' object has no attribute 'internal'

print(getattr(computer1, 'brand'))
setattr(computer2, 'color', 'internal')
print(getattr(computer1, 'name'))
delattr(computer1, 'name')
#print(getattr(computer1, 'name'))   # AttributeError: 'Computer' object has no attribute 'name'

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遛大黄' % self.name)


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

    def call_out(self):
        print('%s:汪汪汪' % self.name)


person1 = Person('小明', 18, '大黄')
dog1 = Dog('大黄', 2, 'yellow')

dog1.call_out()
person1.walk_dog()

3.声明一个圆类,自己确定有哪些属性和方法

class Circle:
    def __init__(self, radius, diameter, area):
        self.radius = radius
        self.diameter = diameter
        self.area = area

    def for_perimeter(self):
        print(3.14*self.diameter)

circle1 =Circle(2, 4, 3.14)
circle1.for_perimeter()

4.创建一个学生类:

属性:姓名,年龄,学号

方法:答到,展示学生信息

创建一个班级类:

属性:学生,班级名

方法:添加学生,删除学生,点名, 求班上学生的平均年龄

class Student:
    def __init__(self, name, age, stu_id):
        self.name = name
        self.age = age
        self.stu_id = stu_id

    def call_roll(self):
        print('%s到!' % self.name, '%s' % self.age, '%s' % self.stu_id)


student1 = Student('Jack', 18, '01')
student2 = Student('Tom', 20, '02')
student1.call_roll()
student2.call_roll()


class ClassGrade:
    def __init__(self, *student, classname):
        self.student = student
        self.classname = classname

    # def add_stu(self):
        # setattr(classgrade1, '%s' % self.classname, '%s' % self.student)


classgrade1 = ClassGrade('Jack', 'Tome', classname=3)
classgrade2 = ClassGrade('Lucy', 'Revin', classname=1)
print(classgrade1.student, classgrade1.classname)
# classgrade1.add_stu()

你可能感兴趣的:(8.8Day014 面向对象基础)