众所周知,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. pat1055. The World's Richest (25)

    1055. The World's Richest (25) 时间限制 400 ms 内存限制 128000 kB 代码长度限制 16000 B 判题程序 Standard 作者 CHEN, Yue ...

  2. 在txt文本后追加内容

    public void CheckLog(string Log)      {             if (File.Exists(LogFile))              {         ...

  3. ECShop配置文件解析

    1. 配置文件位置:/upload/data/config.php 2. 配置解析 <?php // 主机地址 $db_host = ""; // 数据库名称 $db_nam ...

  4. 移植mavlink到stm32详细教程,后面附快速移植方法

    一:准备材料: mavlink源码 stm32串口程序    1.mavlink源码:        a.进入mavlink官网(http://qgroundcontrol.org/mavlink/s ...

  5. 【MFC】获取文件大小的方法

    [转载]原文地址:http://blog.csdn.net/coderwu/article/details/5652056 MFC 下可以通过 CFileStatus 获取文件大小. ULONGLON ...

  6. linux性能测试脚本

    http://linux-bench.com/ What is Linux-Bench? Linux-Bench is a simple script that provides a basic le ...

  7. 重置 file input

    有时用户上传相同附件时也需要触发input[type='file']的change事件,除了将form重置外,还可以将input的value设为空 <input type="file& ...

  8. LeetCode Search Insert Position (二分查找)

    题意: 给一个升序的数组,如果target在里面存在了,返回其下标,若不存在,返回其插入后的下标. 思路: 来一个简单的二分查找就行了,注意边界. class Solution { public: i ...

  9. IE Proxy Swich - IE 代理切换工具

    通过此工具可方便的切换计算机系统代理设置的开关,无需重启IE 来激活设置 下载 环境要求: 可能需要.NET 4.0 以上平台, 其他平台未测试 截图与功能如下 支持快捷方式参数 我个人习惯是在桌面 ...

  10. UOJ#122【NOI2013】树的计数

    [NOI2013]树的计数 链接:http://uoj.ac/problem/122 按BFS序来,如果$B_i$与$B_{i-1}$必须在同一层,那么贡献为0,必须在不同层那么贡献为1,都可以贡献为 ...