zoukankan      html  css  js  c++  java
  • Python 封装

    定义:

      封装不仅仅是隐藏属性和方法是具体明确区分内外,使得类实现者可以修改封装内的东西而不影响外部调用者的代码;而外部使用用者只知道一个接口(函数),只要接口(函数)名、参数不变,使用者的代码永远无需改变。这就提供一个良好的合作基础——或者说,只要接口这个基础约定不变,则代码改变不足为虑。

      封装可分为封装属性与封装函数

    实例:

    #1:封装数据属性:将属性隐藏起来,然后对外提供访问属性的接口,关键是我们在接口内定制一些控制逻辑从而严格控制使用对数据属性的使用
    class People:
        def __init__(self,name,age):
            if not isinstance(name,str):
                raise TypeError('%s must be str' %name)
            if not isinstance(age,int):
                raise TypeError('%s must be int' %age)
            self.__Name=name
            self.__Age=age
        def tell_info(self):
            print('<名字:%s 年龄:%s>' %(self.__Name,self.__Age))
    
        def set_info(self,x,y):
            if not isinstance(x,str):
                raise TypeError('%s must be str' %x)
            if not isinstance(y,int):
                raise TypeError('%s must be int' %y)
            self.__Name=x
            self.__Age=y
    
    p=People('egon',18)
    p.tell_info()
    
    p.set_info('Egon','19')
    p.set_info('Egon',19)
    p.tell_info()
    
    
    
    #2:封装函数属性:为了隔离复杂度
    
    #取款是功能,而这个功能有很多功能组成:插卡、密码认证、输入金额、打印账单、取钱
    #对使用者来说,只需要知道取款这个功能即可,其余功能我们都可以隐藏起来,很明显这么做
    #隔离了复杂度,同时也提升了安全性
    
    class ATM:
        def __card(self):
            print('插卡')
        def __auth(self):
            print('用户认证')
        def __input(self):
            print('输入取款金额')
        def __print_bill(self):
            print('打印账单')
        def __take_money(self):
            print('取款')
    
        def withdraw(self):
            self.__card()
            self.__auth()
            self.__input()
            self.__print_bill()
            self.__take_money()
    
    a=ATM()
    a.withdraw()
  • 相关阅读:
    docker部署springBoot项目
    linux下查看文件内容命令
    nohup后台运行jar与关闭
    nohup优化输出nohup.out日志信息
    Go 精妙的互斥锁设计
    ts找不到全局对象,报错:Cannot find name '__dirname
    定义vscode终端主题色
    element-ui按需引入报错Cannot find module 'babel-preset-es2015' 及多组件引入报错
    c# UWP 墨迹 手写识别
    c# yield return
  • 原文地址:https://www.cnblogs.com/liuxiaowei/p/7414783.html
Copyright © 2011-2022 走看看