2. 封装

封装是指将数据(属性)和操作数据的行为(方法)封装在类中,并控制外部对内部数据的访问权限,让用户通过特定的方法才能操作这些对象。

封装的目的

封装的实现

私有属性和方法

示例

# 此示例示意封装的用法

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, 2000000)
# zhang3.__money -= 2000000
# li4.__money += 2000000
# 35 岁的 张三 有钱 800 元,它学会的技能: ['王者荣耀']
zhang3.show_info()
# 8 岁的 李四 有钱 200 元,它学会的技能: ['Python']
li4.show_info()
视频讲解