类对象之间has a

# has a / is a
class Computer:
    def __init__(self, brand, type, color):
        self.brand = brand
        self.type = type
        self.color = color

    def online(self):
        print('正在上网...')

    def __str__(self):
        msg = '品牌:{},型号:{},颜色:{}.'.format(self.brand, self.type, self.color)
        return msg


class Book:
    def __init__(self, bname, author, num):
        self.bname = bname
        self.author = author
        self.num = num

    def __str__(self):
        msg = '书名:{},作者:{},数量:{}.'.format(self.bname, self.author, self.num)
        return msg


class Student:
    def __init__(self, name, computer, book):
        self.name = name
        self.computer = computer
        self.books = []
        self.books.append(book)

    def borrow_book(self, bname):
        for b in self.books:
            if bname.bname == b.bname:
                print('已经借过此书。')
                break
        else:
            self.books.append(bname)
            print('添加成功.')

    def show_book(self):
        for book in self.books:
            print(book.bname)

    def __str__(self):
        msg = 'name:{},computer:{},book:{}.'.format(self.name, str(self.computer), str(self.books))
        return msg


if __name__ == '__main__':
    def run(c_brand, c_type, c_color, b_name, b_author, b_num, s_name):
        computer = Computer(c_brand, c_type, c_color)
        book = Book(b_name, b_author, b_num)
        stu = Student(s_name, computer, book)

        stu.show_book()

        book1 = Book(b1_name, b1_author, b1_num)
        stu.borrow_book(book1)
        print('*' * 100)

        stu.show_book()


    c_brand, c_type, c_color, b_name, b_author, b_num, s_name = ['Apple', 'MacBook Pro', '银色', '盗墓笔记', '南派三叔', 8,
                                                                 'songsong']

    # borrow book
    b1_name, b1_author, b1_num = ['鬼吹灯', '天下霸唱', 20]
    run(c_brand, c_type, c_color, b_name, b_author, b_num, s_name)

 

posted @ 2021-07-22 10:18  游走在六环  阅读(37)  评论(0)    收藏  举报