• 描述符应用


    '''描述符应用'''
    # class Typed:
    #  def __set__(self, instance, value):
    #     print('set方法执行')
    #     print('instance参数%s' % instance)
    #     print('value参数%s' % value)
    #
    #  def __get__(self, instance, owner):
    #     print('get方法执行')
    #     print('instance参数%s' % instance)
    #     print('owner参数%s' % owner)
    #
    #  def __delete__(self, instance):
    #     print('delete方法执行')
    #     print('instance参数%s' % instance)
    #
    # class People:
    #  name = Typed()
    #  def __init__(self, name, age, salary):
    #     self.name = name
    #     self.age = age
    #     self.salary = salary
    #
    # p1 = People('alex', 18, 10000.55)
    # p1.name
    # p1.name = 'lhf'
    # print(p1.__dict__)
    
    
    # 类实例化所传入参数加上字符类型限制
    class Typed_1:
       def __init__(self, key, expected_type): # ①这里先定义一个__init__,以便作为instance实例属性字典的key值
          self.key = key
          self.expected_type = expected_type
    
       def __set__(self, instance, value):
          if type(value) == self.expected_type:
             instance.__dict__[self.key] = value # ③这里通过self.key作为instance实例属性字典key值
          else:
             raise TypeError('输入类型错误')
    
       def __get__(self, instance, owner):
          return instance.__dict__[self.key]
    
       def __delete__(self, instance):
          instance.__dict__.pop(self.key)
    
    class People_1:
       name = Typed_1('name', str) # ②这里需要传入两个值给__init__
       age = Typed_1('age', int)
       salary = Typed_1('salary', float)
       def __init__(self, name, age, salary):
          self.name = name
          self.age = age
          self.salary = salary
    
    p2 = People_1('小明', 18, 300.33)
    # p3 = People_1(999, 18, 300.33)
    # p4 = People_1('小红', '18', 300.33)
    # p5 = People_1('小亮', 18, 300)
    while True: print('studying...')
  • 相关阅读:
    JavaScript日期处理类库momentjs
    sublime text 2 学习
    node.js代理设置
    使用nodejs将html5 canvas base64编码图片保存为文件
    Sublime Text 2 常用插件介绍
    把silverlight treeview 节点前面的小三角换成自定义的图片
    文件监控
    linux内核中的红黑树代码解析
    static关键字
    红黑树的实现(二)
  • 原文地址:https://www.cnblogs.com/xuewei95/p/14756749.html
Copyright © 2020-2023  润新知