描述符应用 -- 让python变成一个强类型的语言
众所周知,python是一门弱类型的语言,变量可以随意赋值成任意类型,但是通过描述符,我们可以把数据变成强类型的。
我们为数据设置数据描述符,因为数据描述的优先级大于实例属性,所以在给数据赋值的时候会优先出发数据描述符。
普通版
class Typed:
def __init__(self, name, expected_type):
self.name = name
self.expected_type = expected_type def __get__(self, instance, owner):
if instance is None:
return self # 如果实例化用People.name调用的话,就返回Typed的实例name
return instance.__dict__[self.name] def __set__(self, instance, value):
if not isinstance(value, self.expected_type):
raise TypeError('Type error')
instance.__dict__[self.name] = value def __delete__(self, instance):
instance.__dict__.pop(self.name) class People:
name = Typed('name', str)
age = Typed('age', int)
salary = Typed('salary', float) def __init__(self, name, age, salary):
self.name = name
self.age = age
self.salary = salary # p1 = People(123, 18, 3333.3) # TypeError: Type error
# p1=People('egon','18',3333.3) # TypeError: Type error
# p1=People('egon',18,3333) # TypeError: Type error p1 = People('egon', 18, 3333.33) # 正确
用类的装饰器实现
先回顾一下setattr的语法
语法
setattr() 语法:
setattr(object, name, value)
参数
- object -- 对象。
- name -- 字符串,对象属性。
- value -- 属性值。
class Typed:
def __init__(self, name, expected_type):
self.name = name
self.expected_type = expected_type def __get__(self, instance, owner):
if instance is None:
return self
return instance.__dict__[self.name] def __set__(self, instance, value):
if not isinstance(value, self.expected_type):
raise TypeError('type error')
instance.__dict__[self.name] = value def __delete__(self, instance):
self.__dict__.pop(self.name) def typeassert(**kwargs):
def decorator(cls):
for name, expected_type in kwargs.items():
setattr(cls, name, Typed(name, expected_type))
return cls return decorator @typeassert(name=str, age=int, salary=float)
class People:
def __init__(self, name, age, salary):
self.name = name
self.age = age
self.salary = salary p1 = People('edward', 18, 30000.00)
描述符应用 -- 让python变成一个强类型的语言的更多相关文章
- python小知识-__call__和类装饰器的结合使用,数据描述符__get__\__set__\__delete__(描述符类是Python中一种用于储存类属性值的对象)
class Decorator(): def __init__(self, f): print('run in init......') self.f = f def __call__(self, a ...
- python描述符理解
Python中的描述符是一个相对底层的概念 descriptor Any object which defines the methods get(), set(), or delete(). Whe ...
- python2.7高级编程 笔记二(Python中的描述符)
Python中包含了许多内建的语言特性,它们使得代码简洁且易于理解.这些特性包括列表/集合/字典推导式,属性(property).以及装饰器(decorator).对于大部分特性来说,这些" ...
- python描述符(descriptor)、属性(property)、函数(类)装饰器(decorator )原理实例详解
1.前言 Python的描述符是接触到Python核心编程中一个比较难以理解的内容,自己在学习的过程中也遇到过很多的疑惑,通过google和阅读源码,现将自己的理解和心得记录下来,也为正在为了该问题 ...
- 【python】描述符descriptor
开始看官方文档,各种看不懂,只看到一句Properties, bound and unbound methods, static methods, and class methods are all ...
- Python描述符(descriptor)解密(转)
原文:http://www.geekfan.net/7862/ Python中包含了许多内建的语言特性,它们使得代码简洁且易于理解.这些特性包括列表/集合/字典推导式,属性(property).以及装 ...
- Python 描述符(descriptor) 杂记
转自:https://blog.tonyseek.com/post/notes-about-python-descriptor/ Python 引入的“描述符”(descriptor)语法特性真的很黄 ...
- python描述符descriptor(二)
python内置的描述符 python有些内置的描述符对象,property.staticmethod.classmethod,python实现如下: class Property(object): ...
- python高级编程之最佳实践,描述符与属性01
# -*- coding: utf-8 -*- # python:2.x __author__ = 'Administrator' #最佳实践 """ 为了避免前面所有的 ...
随机推荐
- CheatEngine-内存修改
0.备注+待完成 //备注 a). 如果有方括号,就是说CE认为找 到了数值的指针了 //待完成 a). 自动导出外挂 b). 菜单栏中"表单"下的lua是做什么用的 c). CE ...
- MyEclipse8.5配置struts等框架
开发环境:MyEclipse8.5+Tomcat6.5+MySql5.5配置环境:Struts2+Spring2+Hibernate3.1 1.首先创建Java-Web Project工程,选择J2E ...
- JS文本框输入限制
1上面的文本框只能输入数字代码(小数点也不能输入): CODE: <input onkeyup="this.value=this.value.replace(/\D/g,'')&quo ...
- Unity3D C# 学习List数据类型的使用
List<T>类是ArrayList 类的泛型等效类. 该类使用大小可按需动态增加的数组实现 泛型的好处: 它为使用 c#语言编写面向对象程序增加了极大的效力和灵活性.不会强行对值类型进行 ...
- JAVA中数组介绍
一.数组: 数组指一组数据的集合,数组中的每个数据被称作元素. 二.数组定义: 数组类型[] 数组名 = new 数组类型[元素个数或数组长度]: (注意:等号前面的[]里面不能写任何东西) 也可以以 ...
- mui蒙版使用例子
<!DOCTYPE html><html><head> <meta charset="utf-8"> <meta name=& ...
- sass相关随笔
安装 下载ruby并且安装 点击这里 打开命令行输入 gem install sass 我使用的是sublime text3 还需要下载三个插件 sass -- 可以帮助你语法高亮 sass buil ...
- datagrid数据表格使用总结
一.加载的css文件 easyui 基本样式: <link href="../easyui/easyui1.5.css" rel="stylesheet" ...
- 在SQL中查看文件组中有哪些表
SELECT o.[name], o.[type], i.[name], i.[index_id], f.[name] FROM sys.indexes i INNER JOIN sys.filegr ...
- 初学python,感受和C的不同
从开始看Python到现在也有半个多月了,前后看了Python核心编程和Dive into Python两本书.话说半个月看两本,是个人都知道有多囫囵吞枣,这也是因为我暂时没有需求拿这个做大型开发,主 ...