zoukankan      html  css  js  c++  java
  • python学习之类装饰器应用和数据描述符相结合

    def deco(**kwargs):
    def wrapper(obj):
    for key, val in kwargs.items():
    setattr(obj, key, Typed(key, val))
    return obj

    return wrapper


    class Typed:
    def __init__(self, key, expected_type):
    self.key = key
    self.expected_type = expected_type

    def __get__(self, instance, owner):
    return instance.__dict__[self.key]

    def __set__(self, instance, value):
    if not isinstance(value, self.expected_type):
    raise TypeError('%s 传入的类型不是%s' % (self.key, self.expected_type))
    instance.__dict__[self.key] = value

    def __delete__(self, instance):
    pass


    @deco(name=str, age=int, gender=str, height=int)
    class People:
    def __init__(self, name, age, gender, height):
    self.name = name
    self.age = age
    self.gender = gender
    self.height = height


    p1 = People('alan', 18, 'boy', 185)
    print(People.__dict__)

    ****************************************************************
    <__main__.lazyproperty object at 0x0000000002933320> 实例
    <__main__.Room object at 0x0000000002933390> 实例
    <class '__main__.Room'> 类
    ****************************************************************

  • 相关阅读:
    偏函数 匿名函数 高阶函数 map filter reduce
    函数
    Python的字符串格式化
    集合
    列表 元组 字典
    字符串
    数字
    Python基础-杂项
    Java 和C/C++的“语法”上的差异!
    MySQL基础原创笔记(一)
  • 原文地址:https://www.cnblogs.com/jinpingzhao/p/12916274.html
Copyright © 2011-2022 走看看