众所周知,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变成一个强类型的语言的更多相关文章

  1. python小知识-__call__和类装饰器的结合使用,数据描述符__get__\__set__\__delete__(描述符类是Python中一种用于储存类属性值的对象)

    class Decorator(): def __init__(self, f): print('run in init......') self.f = f def __call__(self, a ...

  2. python描述符理解

    Python中的描述符是一个相对底层的概念 descriptor Any object which defines the methods get(), set(), or delete(). Whe ...

  3. python2.7高级编程 笔记二(Python中的描述符)

    Python中包含了许多内建的语言特性,它们使得代码简洁且易于理解.这些特性包括列表/集合/字典推导式,属性(property).以及装饰器(decorator).对于大部分特性来说,这些" ...

  4. python描述符(descriptor)、属性(property)、函数(类)装饰器(decorator )原理实例详解

     1.前言 Python的描述符是接触到Python核心编程中一个比较难以理解的内容,自己在学习的过程中也遇到过很多的疑惑,通过google和阅读源码,现将自己的理解和心得记录下来,也为正在为了该问题 ...

  5. 【python】描述符descriptor

    开始看官方文档,各种看不懂,只看到一句Properties, bound and unbound methods, static methods, and class methods are all ...

  6. Python描述符(descriptor)解密(转)

    原文:http://www.geekfan.net/7862/ Python中包含了许多内建的语言特性,它们使得代码简洁且易于理解.这些特性包括列表/集合/字典推导式,属性(property).以及装 ...

  7. Python 描述符(descriptor) 杂记

    转自:https://blog.tonyseek.com/post/notes-about-python-descriptor/ Python 引入的“描述符”(descriptor)语法特性真的很黄 ...

  8. python描述符descriptor(二)

    python内置的描述符 python有些内置的描述符对象,property.staticmethod.classmethod,python实现如下: class Property(object): ...

  9. python高级编程之最佳实践,描述符与属性01

    # -*- coding: utf-8 -*- # python:2.x __author__ = 'Administrator' #最佳实践 """ 为了避免前面所有的 ...

随机推荐

  1. ACdream 1216——Beautiful People——————【二维LIS,nlogn处理】

    Beautiful People Special Judge Time Limit: 2000/1000MS (Java/Others) Memory Limit: 128000/64000KB (J ...

  2. 如何在数据库中导入excel文件内的数据

    如何在数据库中轻松导入excel格式的文件 1)打开sql server,找到要导入数据的数据库,右键>>任务>>导入数据 2)按照图示选择要导入的excel 3)选择导入到哪 ...

  3. Java项目—嗖嗖移动业务大厅

    嗖嗖移动业务大厅包类(如下图): SosoMgr: package cn.biz; import java.util.Scanner; import cn.common.Common; import ...

  4. Duplicate Emails

    Write a SQL query to find all duplicate emails in a table named Person. +----+---------+ | Id | Emai ...

  5. webpack源码之ast简介

    什么是AST 树是一种重要的数据结构,由根结点和若干颗子树构成的. 根据结构的不同又可以划分为二叉树,trie树,红黑树等等.今天研究的对象是AST,抽象语法树,它以树状的形式表现编程语言的语法结构, ...

  6. Hadoop 分片、分组与排序

    首先需要明确的是,hadoop里的key一定要是可排序的,要么key自身实现了WritableComparator接口,要么有一个排序类可以对key进行排序.如果key本身不实现WritableCom ...

  7. VMware虚拟机配置文件(.vmx)损坏修复

    我的虚拟机为VM14    装的ubuntu14.04server版 遇到ubuntu打不开,上网查阅了博客写的解决办法,尝试并解决了,以下分享个人心得: 首先进入虚拟机中系统安装的位置 查看日志文件 ...

  8. vs2010 opencv2.4.10 配置过程出现的问题 & mfc打开图片

    配置参考网址: http://blog.csdn.net/zy122121cs/article/details/49180541 无法启动程序,系统找不到指定的文件:原因是程序编译有错误(不是路径之类 ...

  9. Python 随笔之Redis

    Python学习记录 ——redis 2018-03-07 Redis是一个开源的使用ANSI C语言编写.支持网络.可基于内存亦可持久化的日志型.Key-Value数据库,并提供多种语言的API.从 ...

  10. cesium加载shp格式数据

    方法一: shp格式转换为GeoJson格式并加载 首先注意shp的坐标系,要转换为WGS84,使用arcgis或QGIS 工具:http://mapshaper.org/: 注意:export时,输 ...