描述符应用 -- 让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' #最佳实践 """ 为了避免前面所有的 ...
随机推荐
- VirtualBox 在Centos 7 中安装增强功能 (共享文件夹)
1.分配光驱 2.安装相关依赖包 yum install -y bzip2 gcc gcc-devel gcc-c++ gcc-c++-devel make kernel-d 3.创建临时文件夹 mk ...
- int,long,long long的数据范围
unsigned int 0-4294967295 int 2147483648-2147483647 unsigned long 0-4294967295long 2147483 ...
- 如何远程连接非默认端口SQL Server
SQL Server Management Studio建立远程SQL连接 连接的时候写: 127.0.0.1,49685\sqlexpress 记得使用逗号,不是冒号
- 初学struts2-入门案列
1.所需类库 <dependency> <groupId>junit</groupId> <artifactId>junit</artifactI ...
- .NET导出excel方法
//导出 private string outFileName = ""; private string fullFilename = ""; private ...
- 三、css 和 js 的装载与执行
一个网站在浏览器端是如何渲染的? 一.html 页面加载渲染的过程. 请求回来最先应该是HTML,从一个字节流转换成字符流,浏览器拿到字符流,然后浏览器端进行相应的词法分析成相应的token,然后不断 ...
- Android 应用开机自启和无需权限开启悬浮框
开机自启主要自定义广播接收类,且需要在清单文件中注册,不要在代码中动态注册. <uses-permission android:name="android.permission.REC ...
- .gitignore梳理
参考来源: https://www.cnblogs.com/kevingrace/p/5690241.html 对于经常使用Git的朋友来说,.gitignore配置一定不会陌生.废话不说多了,接下来 ...
- HDU3577 线段树(区间更新)
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=3577 ,普通的线段树区间更新题目,较简单. 相当于一个区间覆盖问题,有一点要注意的就是叶子节点是一个长 ...
- IOS 监听键盘的通知(NSNotificationCenter)
通知方法: /** * 当键盘改变了frame(位置和尺寸)的时候调用 */ - (void)keyboardWillChangeFrame:(NSNotification *)note { // 设 ...