计算机基础 - 封装

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

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()

转载于:https://www.cnblogs.com/allen2333/p/9297384.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值