计算机基础 - 封装

Posted allen2333

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了计算机基础 - 封装相关的知识,希望对你有一定的参考价值。

封装这个概念贯穿码农工作的日常, 意义:

1. 隐藏数据,对外提供操作数据的接口,并可以对操作数据进行严格控制。

class Teacher:

    def __init__(self, name, age):
        self.__name = name
        self.__age = age

    def tell_info(self):
        print(‘姓名:{name}, 年龄:{age}‘.format(name=self.__name, age=self.__age))

    def set_info(self, name, age):

        # 对输入进行检测,对操作数据属性进行严格控制
        if not isinstance(name, str):
            raise TypeError(‘name must be string‘)
        if not isinstance(age, int):
            raise TypeError(‘age must be int‘)
        # 过了检测后,赋值
        self.__name = name
        self.__age = age

betty = Teacher(‘betty‘, 25)
betty.tell_info()
#betty.set_info(1, 1)
#betty.set_info(‘x‘, ‘x‘)
betty.set_info(‘allen‘, 23)
betty.tell_info()

2. 隔离复杂度

# 取款是功能,由插卡、密码认证、输入金额、打印账单、取钱组成
# 使用者只知道这个接口完成取款操作,不需要知道细节
# 这样做隔离了复杂度,提高了安全性

class ATM:

    def __insert_card(self):
        print(‘insert the freaking card‘)

    def __auth(self):
        print(‘password auth‘)

    def __input(self):
        print(‘input money‘)

    def __print_bill(self):
        print(‘print bill‘)

    def __take_money(self):
        print(‘take money‘)

    def withdraw(self):
        self.__insert_card()
        self.__auth()
        self.__input()
        self.__print_bill()
        self.__take_money()

Automatic_Teller_Machine = ATM()
Automatic_Teller_Machine.withdraw()

以上是关于计算机基础 - 封装的主要内容,如果未能解决你的问题,请参考以下文章

VSCode自定义代码片段14——Vue的axios网络请求封装

VSCode自定义代码片段14——Vue的axios网络请求封装

VSCode自定义代码片段14——Vue的axios网络请求封装

回归 | js实用代码片段的封装与总结(持续更新中...)

常用Javascript代码片段集锦

Python小白到老司机,快跟我上车!基础篇(十三)