zoukankan      html  css  js  c++  java
  • python描述符

    class Type:
        def __init__(self, key, expect_type):
            self.key = key
            self.expect_type = expect_type
    
        def __get__(self, instance, owner):
            print('执行get方法')
            return instance.__dict__[self.key]
    
        def __set__(self, instance, value):
            print('执行set方法')
            if not isinstance(value, self.expect_type):
                raise TypeError('你传入的不是',self.expect_type)
    
            instance.__dict__[self.key]=value
    
        def __delete__(self, instance):
            print('执行delete方法')
            instance.__dict__.pop(self.key)
    
    
    class People:
        name = Type('name', str)
        age = Type('age', int)
    
        def __init__(self, name, age):
            self.name = name
            self.age = age
    
    p = People('alex', 11)
    print(p.name)

    class Type:
    def __init__(self, key, expect_type):
    self.key = key
    self.expect_type = expect_type

    def __get__(self, instance, owner):
    print('执行get方法')
    return instance.__dict__[self.key]

    def __set__(self, instance, value):
    print('执行set方法')
    if not isinstance(value, self.expect_type):
    raise TypeError('你传入的不是',self.expect_type)

    instance.__dict__[self.key]=value

    def __delete__(self, instance):
    print('执行delete方法')
    instance.__dict__.pop(self.key)


    def deco(**kwargs): # kwargs = {'name':str, 'age': int}
    def wrapper(obj): # obj = People
    print('--->',kwargs)
    print('类名',obj)
    for key, val in kwargs.items(): # ('name',str),('age',int)

    setattr(obj, key, Type(key, val))
    return obj
    print(kwargs)
    return wrapper


    @deco(name=str, age=int) # @wrapper ==> People= wrapper(People)
    class People:
    def __init__(self, name, age):
    self.name = name
    self.age = age


    p = People('alex', 11)

    print(p.__dict__)
  • 相关阅读:
    HDU 1258 Sum It Up(Dfs)
    HDU 1501 Zipper(Dfs记忆化搜索)
    HDU 1075 What Are You Talking About (字典树)
    HDU 1251 统计难题(字典树)
    HDU 1518 Square(Dfs)
    %与mod的区别
    有向无向欧拉回路通路的判断
    HDU 1104 Remainder(BFS打印路径+数论)(%与mod的区别)
    写给还在怀念骑士(3.0 2.0 Online 私服)的刀狼
    HUD 1312 Red and Black(用深搜写的)
  • 原文地址:https://www.cnblogs.com/majianyu/p/10248144.html
Copyright © 2011-2022 走看看