规范
本 PEP 规定了一组抽象基类(Abstract Base Class),并提出了一个实现某些方法的通用策

略。它使用了来自于PEP 3119的术语,但是该层次结构旨在对特定类集的任何系统方法都有意

义。

标准库中的类型检查应该使用这些类,而不是具体的内置类型。

数值类
我们从 Number 类开始,它是人们想象的数字类型的模糊概念。此类仅用于重载;它不提供任

何操作。

class Number(metaclass=ABCMeta): pass
大多数复数(complex number)的实现都是可散列的,但是如果你需要依赖它,则必须明确地

检查:此层次结构支持可变的数。

class Complex(Number):
“”"Complex defines the operations that work on the builtin complex type.

In short, those are: conversion to complex, bool(), .real, .imag,
+, -, *, /, **, abs(), .conjugate(), ==, and !=.If it is given heterogenous arguments, and doesn't have special
knowledge about them, it should fall back to the builtin complex
type as described below.
"""@abstractmethod
def __complex__(self):"""Return a builtin complex instance."""def __bool__(self):"""True if self != 0."""return self != 0@abstractproperty
def real(self):"""Retrieve the real component of this number.This should subclass Real."""raise NotImplementedError@abstractproperty
def imag(self):"""Retrieve the real component of this number.This should subclass Real."""raise NotImplementedError@abstractmethod
def __add__(self, other):raise NotImplementedError@abstractmethod
def __radd__(self, other):raise NotImplementedError@abstractmethod
def __neg__(self):raise NotImplementedErrordef __pos__(self):"""Coerces self to whatever class defines the method."""raise NotImplementedErrordef __sub__(self, other):return self + -otherdef __rsub__(self, other):return -self + other@abstractmethod
def __mul__(self, other):raise NotImplementedError@abstractmethod
def __rmul__(self, other):raise NotImplementedError@abstractmethod
def __div__(self, other):"""a/b; should promote to float or complex when necessary."""raise NotImplementedError@abstractmethod
def __rdiv__(self, other):raise NotImplementedError@abstractmethod
def __pow__(self, exponent):"""a**b; should promote to float or complex when necessary."""raise NotImplementedError@abstractmethod
def __rpow__(self, base):raise NotImplementedError@abstractmethod
def __abs__(self):"""Returns the Real distance from 0."""raise NotImplementedError@abstractmethod
def conjugate(self):"""(x+y*i).conjugate() returns (x-y*i)."""raise NotImplementedError@abstractmethod
def __eq__(self, other):raise NotImplementedError# __ne__ is inherited from object and negates whatever __eq__ does.

Real抽象基类表示在实数轴上的值,并且支持内置的float的操作。实数(Real number)是完

全有序的,除了 NaN(本 PEP 基本上不考虑它)。

class Real(Complex):
“”"To Complex, Real adds the operations that work on real numbers.

In short, those are: conversion to float, trunc(), math.floor(),
math.ceil(), round(), divmod(), //, %, <, <=, >, and >=.Real also provides defaults for some of the derived operations.
"""# XXX What to do about the __int__ implementation that's
# currently present on float?  Get rid of it?@abstractmethod
def __float__(self):"""Any Real can be converted to a native float object."""raise NotImplementedError@abstractmethod
def __trunc__(self):"""Truncates self to an Integral.Returns an Integral i such that:* i>=0 iff self>0;* abs(i) <= abs(self);* for any Integral j satisfying the first two conditions,abs(i) >= abs(j) [i.e. i has "maximal" abs among those].i.e. "truncate towards 0"."""raise NotImplementedError@abstractmethod
def __floor__(self):"""Finds the greatest Integral <= self."""raise NotImplementedError@abstractmethod
def __ceil__(self):"""Finds the least Integral >= self."""raise NotImplementedError@abstractmethod
def __round__(self, ndigits:Integral=None):"""Rounds self to ndigits decimal places, defaulting to 0.If ndigits is omitted or None, returns an Integral,otherwise returns a Real, preferably of the same type asself. Types may choose which direction to round half. Forexample, float rounds half toward even."""raise NotImplementedErrordef __divmod__(self, other):"""The pair (self // other, self % other).Sometimes this can be computed faster than the pair ofoperations."""return (self // other, self % other)def __rdivmod__(self, other):"""The pair (self // other, self % other).Sometimes this can be computed faster than the pair ofoperations."""return (other // self, other % self)@abstractmethod
def __floordiv__(self, other):"""The floor() of self/other. Integral."""raise NotImplementedError@abstractmethod
def __rfloordiv__(self, other):"""The floor() of other/self."""raise NotImplementedError@abstractmethod
def __mod__(self, other):"""self % otherSeehttps://mail.python.org/pipermail/python-3000/2006-May/001735.htmland consider using "self/other - trunc(self/other)"instead if you're worried about round-off errors."""raise NotImplementedError@abstractmethod
def __rmod__(self, other):"""other % self"""raise NotImplementedError@abstractmethod
def __lt__(self, other):"""< on Reals defines a total ordering, except perhaps for NaN."""raise NotImplementedError@abstractmethod
def __le__(self, other):raise NotImplementedError# __gt__ and __ge__ are automatically done by reversing the arguments.
# (But __le__ is not computed as the opposite of __gt__!)# Concrete implementations of Complex abstract methods.
# Subclasses may override these, but don't have to.def __complex__(self):return complex(float(self))@property
def real(self):return +self@property
def imag(self):return 0def conjugate(self):"""Conjugate is a no-op for Reals."""return +self

我们应该整理 Demo/classes/Rat.py,并把它提升为 Rational.py 加入标准库。然后它将实现

有理数(Rational)抽象基类。

class Rational(Real, Exact):
“”".numerator and .denominator should be in lowest terms."""

@abstractproperty
def numerator(self):raise NotImplementedError@abstractproperty
def denominator(self):raise NotImplementedError# Concrete implementation of Real's conversion to float.
# (This invokes Integer.__div__().)def __float__(self):return self.numerator / self.denominator

最后是整数类:

class Integral(Rational):
“”“Integral adds a conversion to int and the bit-string operations.”""

@abstractmethod
def __int__(self):raise NotImplementedErrordef __index__(self):"""__index__() exists because float has __int__()."""return int(self)def __lshift__(self, other):return int(self) << int(other)def __rlshift__(self, other):return int(other) << int(self)def __rshift__(self, other):return int(self) >> int(other)def __rrshift__(self, other):return int(other) >> int(self)def __and__(self, other):return int(self) & int(other)def __rand__(self, other):return int(other) & int(self)def __xor__(self, other):return int(self) ^ int(other)def __rxor__(self, other):return int(other) ^ int(self)def __or__(self, other):return int(self) | int(other)def __ror__(self, other):return int(other) | int(self)def __invert__(self):return ~int(self)# Concrete implementations of Rational and Real abstract methods.
def __float__(self):"""float(self) == float(int(self))"""return float(int(self))@property
def numerator(self):"""Integers are their own numerators."""return +self@property
def denominator(self):"""Integers have a denominator of 1."""return 1

运算及__magic__方法的变更
为了支持从 float 到 int(确切地说,从 Real 到 Integral)的精度收缩,我们提出了以下

新的 magic 方法,可以从相应的库函数中调用。所有这些方法都返回 Intergral 而不是

Real。

trunc(self):在新的内置 trunc(x) 里调用,它返回从 0 到 x 之间的最接近 x 的

Integral。
floor(self):在 math.floor(x) 里调用,返回最大的 Integral <= x。
ceil(self):在 math.ceil(x) 里调用,返回最小的 Integral > = x。
round(self):在 round(x) 里调用,返回最接近 x 的 Integral ,根据选定的类型作四

舍五入。浮点数将从 3.0 版本起改为向偶数端四舍五入。(译注:round(2.5) 等于 2,

round(3.5) 等于 4)。它还有一个带两参数的版本__round__(self, ndigits),被 round(x,

ndigits) 调用,但返回的是一个 Real。
在 2.6 版本中,math.floor、math.ceil 和 round 将继续返回浮点数。

float 的 int() 转换等效于 trunc()。一般而言,int() 的转换首先会尝试__int__(),如果

找不到,再尝试__trunc__()。

complex.{divmod, mod, floordiv, int, float} 也消失了。提供一个好的错误消息来帮

助困惑的搬运工会很好,但更重要的是不出现在 help(complex) 中。

给类型实现者的说明
实现者应该注意使相等的数字相等,并将它们散列为相同的值。如果实数有两个不同的扩展,

这可能会变得微妙。例如,一个复数类型可以像这样合理地实现 hash():

def hash(self):
return hash(complex(self))
但应注意所有超出了内置复数范围或精度的值。

添加更多数字抽象基类
当然,数字还可能有更多的抽象基类,如果排除了添加这些数字的可能性,这会是一个糟糕的

等级体系。你可以使用以下方法在 Complex 和 Real 之间添加MyFoo:

class MyFoo(Complex): …
MyFoo.register(Real)
实现算术运算
我们希望实现算术运算,使得在混合模式的运算时,要么调用者知道如何处理两种参数类型,

要么将两者都转换为最接近的内置类型,并以此进行操作。

对于 Integral 的子类型,这意味着__add__和__radd__应该被定义为:

class MyIntegral(Integral):

def __add__(self, other):if isinstance(other, MyIntegral):return do_my_adding_stuff(self, other)elif isinstance(other, OtherTypeIKnowAbout):return do_my_other_adding_stuff(self, other)else:return NotImplementeddef __radd__(self, other):if isinstance(other, MyIntegral):return do_my_adding_stuff(other, self)elif isinstance(other, OtherTypeIKnowAbout):return do_my_other_adding_stuff(other, self)elif isinstance(other, Integral):return int(other) + int(self)elif isinstance(other, Real):return float(other) + float(self)elif isinstance(other, Complex):return complex(other) + complex(self)else:return NotImplemented亚马逊测评 www.yisuping.com

Python 中的数字到底是什么?相关推荐

  1. ​Python 中的数字到底是什么?

    ???? "Python猫" ,一个值得加星标的公众号 花下猫语:在 Python 中,不同类型的数字可以直接做算术运算,并不需要作显式的类型转换.但是,它的"隐式类型转 ...

  2. Python基础与拾遗1:Python中的数字

    Python基础与拾遗1:Python中的数字 写在前面 数字常量 表达式操作符 变量 除法 复数 二进制,八进制与十六进制 常用内置数学工具 小数与分数 集合 布尔 写在前面 转瞬之间,笔者已经有一 ...

  3. python中的数字类型格式与运算_Python中的数字类型格式与运算

    出品 Python中的数字(Digital)与数学中的数字相同,可以通过各种各样的运算符实现各种计算,在Python中数字类型的数据格式分为以下几种: 1.整数型(integer) 2.浮点数(flo ...

  4. python pow和**_第005篇:Python中的数字

    既然文章是写给财务人员的,那么我就首先讲Python的数字. Python的数字有两类: 整数,英文叫做:integer,如:1,3,6,20,100等等 浮点数,英文叫做:float,如:1.2,6 ...

  5. c++用一级运算比较大小_Python 学习笔记:Python 中的数字和数字型运算

    在 Python 数据类型知识中我们已经初步认识了几种 Python 中的数据类型,现在我们更详细的学习一下 数字型 以及 数字型运算. 我们已经知道了 Python 中的数字分为两种,分别是整数 i ...

  6. python中mod是什么意思_【python中,mod_python到底做了些什么呢?】mod python 教程

    python 编程小白 ,不会用doctest 请大神指教怎么用!! >>> >>> def is_between(v, lower, higher): ...   ...

  7. python中数字应该用什么表示_8.python中的数字

    python中数字对象的创建如下, a = 123b= 1.23c= 1+1j 可以直接输入数字,然后赋值给变量. 同样也可是使用类的方式: a = int(123) b= float(1.23) c ...

  8. python中的JSON到底怎么用?

    前言 最近在学习python爬虫,在对数据进行持久化存储的时候,会选择使用json格式的数据进行存储,由此就引发了一个问题,python中的JSON库到底咋用? 以前使用JavaScript中Json ...

  9. python中星号数字乘字符串_Python系列-数字和字符串

    数字 Python的数学计算功能强大而简单,可以计算各种复杂的运算.数字分整型(integer)和浮点型(float),即整数和小数.这一节中,介绍的是简单的数字运算. 先来看一段代码: >&g ...

最新文章

  1. Linux 多线程同步机制:互斥量、信号量、条件变量
  2. Forrester:2011年Q2数据库审计与实时保护市场分析报告【更新】
  3. c#中的protected和internal
  4. CSS弹出二级多列菜单和DIV布局实例 - 仿IBM官网首页
  5. 3dmax导出fbx ue4_Maya建模师分享干货的时间到啦,教你用UE4如何导入动画
  6. 5.6 Column Attribute
  7. python mysql实例_Python 操作MySQL详解及实例
  8. 实例:使用纹理对象创建Sprite对象
  9. 上过云么?一行代码秒上云体验过么?
  10. 高级IO--5种及select、poll、epoll的原理、执行以及优缺点
  11. 2021年中国传送控制器市场趋势报告、技术动态创新及2027年市场预测
  12. 泛微数字化督查督办平台:不见面也能高效落实工作、管理到位
  13. php 微信下载临时素材,php 微信开发之新增上传/获取下载临时素材
  14. 用增广矩阵的秩判断N线性方程的解的个数
  15. 2008年胡润中国富豪榜榜单(401-500名)
  16. VMware虚拟机装windows xp系统
  17. 如何防止工具(八门神器)进行内存修改(转)
  18. JavaScript中minio的使用
  19. Apple Watch 的传感器
  20. python 波动率锥_推广 || 12个小时干货分享!上海财大期权实战特训课程(11月)...

热门文章

  1. 有一种机遇叫5G速度,有一种痛叫5G数据
  2. 用Jenkins连接腾讯企业邮箱,在构建任务失败时给自己发邮件提醒
  3. java架构师培训:java最佳测试框架JBehave的基本介绍
  4. Word文档转PPT(仅文字)
  5. sdkman OpenSSL SSL_connect: Connection reset
  6. 后端开发总结(3):代码健壮性:容错处理+测试
  7. 图片爬虫——unsplash爬虫
  8. 王码五笔造词生成的文件备份
  9. java doc转为pdf_Java利用openoffice将doc、docx转为pdf实例代码
  10. 男人应该摒弃“处女情结”