zoukankan      html  css  js  c++  java
  • 继承的方式完成包装

    class Foo:
       def __init__(self, name):
          self.name = name
    
       def __setattr__(self, key, value):
          if type(value) is str: # 根据属性值类型进行判断,如果为字符串类型则成功添加
             self.__dict__[key] = value
          else:
             print('数据类型错误')
    
       def __getattr__(self, item):
          print('你找的%s属性不存在' % item)
    
       def __delattr__(self, item):
          self.__dict__.pop[item]
    
    f1 = Foo('alex')
    print(f1.name)
    
    
    '''包装:python为大家提供了标准数据类型,以及丰富的内置方法,其实在很多场景下我们都需要基于标准数据类型来定制我们自己的数据类型,新增/改写方法,这就用到了我们刚学的继承/派生知识(其它的标准类型均可以通过下面的方式进行二次加工)'''
    class List(list): # list类实例化后的对象是一个列表,也就是说实例本身self就是一个列表
       def show_midlle(self):
          index = len(self) // 2
          return self[index]
    
       def append(self, object):
          if type(object) is str:
             # list.append(self, object) # 父类调用自己的方法,属于类调用自己的函数属性
             super().append(object) # 等同于super(List, self).append(object)
          else:
             print('只能添加字符串类型')
    
    l1 = list('hello')
    print(l1, type(l1)) # ['h', 'e', 'l', 'l', 'o'] <class 'list'>
    
    l2 = List('hello')
    print(l2, type(l2)) # ['h', 'e', 'l', 'l', 'o'] <class '__main__.List'>
    print(List.__dict__)
    print(l2.show_midlle())
    
    l2.append('alex')
    print(l2)
    l2.append(1)
    print(l2)
    
    
    # clear()加权限限制
    class List(list):
       def __init__(self, item, tag=False):
          super().__init__(item)
          self.tag = tag
    
       def append(self, p_object):
          if not isinstance(p_object, str):
             raise TypeError
          super().append(p_object)
    
       def clear(self):
          if not self.tag:
             raise PermissionError
          super().clear()
    
    l = List([1,2,3],False)
    print(l)
    print(l.tag)
    
    l.append('saf')
    print(l)
    
    # l.clear() # 异常
    # print(l)
    
    l.tag = True
    l.clear()
    print(l)
    while True: print('studying...')
  • 相关阅读:
    MySQL 约束
    MySQL 基础
    LeetCode-Backtracking-Easy 回溯算法
    cookie session区别
    mac环境下支持PHP调试工具xdebug,phpstorm监听
    dede修改移动文档的js
    ajax是怎么发请求的和浏览器发的请求一样吗?cookie
    linux命令
    mysql里的sql函数
    nginx启动
  • 原文地址:https://www.cnblogs.com/xuewei95/p/14709083.html
Copyright © 2011-2022 走看看