class CheckString: def __init__(self, variable_type): self.variable_type = variable_type def __set__(self, instance, value): print(‘__set__:‘, value) self.value = "error:类型错误" if self.variable_type == ‘str‘: self.value = value if isinstance(value, str) else "error:类型错误" def __get__(self, instance, owner): print("__get__") return self.value pass def __delete__(self, instance): pass class InfoModel: name = CheckString(variable_type=‘str‘) if __name__ == ‘__main__‘: info = InfoModel() info.name = "北门吹雪" print(info.name)
通过另外一个类来描叙类变量的属性类型,这个是ORM实现的核心基础
给属性赋值会调用 __set__方法,访问属性则会调用 __get__方法,则可以获取字段的对象和其值,删除字段时候则调用 __delete__方法
原文地址:https://www.cnblogs.com/2bjiujiu/p/9142647.html
时间: 2024-10-11 16:17:49