第十四章、面相对象编程

1. 面向对象编程概述

面向对象编程

面向对象编程(Object-Oriented Programming,简称OOP)是一种软件设计思想。他是用对象来描述现实世界的各种关系和操作,用类来规范对象的行为的编程思想。

面向对象的编程语言的特征:

优点:

面向对象示例

有两个人

行为

事情

用下面的类来描述人类的行为。

class Human:
    def __init__(self, n, a):
    def teach(self, other, subject): 
    def works(self, money): 
    def borrow(self, other, money): 
    def show_info(self):

示例

class Human:
    def __init__(self, n, a):
        self.name = n  # 姓名
        self.age = a  # 年龄
        self.money = 0  # 钱数为0
        self.skills = []  # 学到的技能

    def teach(self, other, subject):
        other.skills.append(subject)
        print(self.name, "教", other.name, '学', subject)

    def works(self, money):
        self.money += money
        print(self.name, '工作赚了', money, '元钱')

    def borrow(self, other, money):
        '描述一个人向其它人借钱的行为,它人有钱必借,不够不借'
        if other.money > money:
            other.money -= money
            self.money += money
            print(self.name, "向", other.name, '借', money, '元钱')
        else:
            print(other.name, '没有', money, '元钱,不能借给', self.name)

    def show_info(self):
        print(self.age, '岁的', self.name,
            '有钱', self.money, '元,他学会的技能:', self.skills)

# 事情
zhang3 = Human('张三', 35)
li4 = Human('李四', 10)
# 张三 教 李四 学 python
zhang3.teach(li4, 'Python')
# 李四 教 张三 学 王者荣耀
li4.teach(zhang3, '王者荣耀')
# 张三 工作赚了 1000 元钱
zhang3.works(1000)
# 李四 向 张三 借 200 元钱
li4.borrow(zhang3, 200)
# 35 岁的 张三 有钱 800 元,它学会的技能: ['王者荣耀']
zhang3.show_info()
# 8 岁的 李四 有钱 200 元,它学会的技能: ['Python']
li4.show_info()

视频讲解