Py学习  »  Python

Python3中的常量和部分详解

belingud • 4 年前 • 251 次点击  
阅读 28

Python3中的常量和部分详解

Python3的内置常量

在Python解释器中,有少量的常量存在于内置命名空间中

所谓常量就是指不变化的量,虽然在python中的常量有可以被重新赋值的常量,但是强烈建议不要对其重新赋值,否则会影响python解释器正确执行python程序

False:

  • bool类型的假值
  • 不可赋值

True

  • bool类型的真值,给True或False赋值是非法的,会引发SyntaxError
  • 不可赋值

None

  • NoneType类型的唯一值.None经常用于表示缺少值,当因为默认参数未传递给函数时.给None赋值也是非法的,后引发SyntaxError
  • 不可赋值

NotImplemented

  • 二进制特殊方法应返回特殊值(例如,__eq__(),__lt__(),__add__(),__rsub__()等)表示操作没有针对其他类型实现,为了相同的目的可以通过就地二进制特殊方法(例如__imul__(),__rightnd__()等)返回,它的逻辑为真.
  • 对其赋值不会抛错,但是不应该对其赋值,会影响解释器对程序正常的执行

注解:当二进制(或就地)方法返回NotImplemented时,解释器将常识对另一种类型(或其他一些回滚操作,取决于运算符)的反射操作。 如果所有尝试都返回NotImplemented,则解释器将引发适当的异常。 错误返回的NotImplemented将导致误导性错误消息或返回到Python代码中的NotImplemented值。

NotImplemented是说明当前代码没有实现对调用方法的支持,不错产生错误.

它的布尔值为真:

>>> bool(NotImplemented)
True
复制代码

下面用代码展示这个常量的作用,定义两个类,实现了__eq__()方法:

class A:
    def __init__(self, value):
        self.value = value
    def __eq__(self, other):
      """
      传进的other是A的实例或者B的实例,都调用此方法进行比较,
      其他情况返回NotImplemmented
      """
        if isinstance(other, A):
            print(f'Comparing an A with another A')
            return other.value == self.value
        if isinstance(other, B):
            print(f'Comparing an A with a B')
            return other.value == self.value
        print('could not compare A with other class')
        return NotImplemented
class B:
    def __init__(self, value):
        self.value = value
    def __eq__(self, other):
      """
      只有other是B的实例时才调用这个方法进行比较,其他情况返回
      NotImplemented
      """
        if isinstance(other, B):
            print(f'Comparing an B with another B')
            return other.value == self.value
        print('could not compare B with other class')
        return NotImplemented
复制代码

在代码中实例化两个类,分别进行比较,查看调用方法的不同:

>>> a1 = A(1)
>>> b1 = B(1)
>>> a1 == b1
Comparing an A with a B
True
>>> a1 == a1
Comparing an A with another A
True
复制代码

如上例,运行a1 == b1,首先调用a1__eq__()方法,对前后两个值a1和b1比较,

同样a1 == a1调用A的__eq__()方法

>>> b1 == b1
Comparing a B with another B
True
复制代码

调用b1的__eq__()方法.

>>> b1 == a1
Could not compare B against the other class
Comparing an A with a B
True
复制代码

如上面代码所示,b1和a1进行比较时,会首先调用B类中的__eq__()方法,即b1.__eq__(a1),得到控制台信息Could not compare B against the other class,返回NotImpletemented,这个常量告诉解释器,对应的方法没有在该类中实现,让其尝试调用a1的__eq__()方法,得到控制台信息Comparing an A with a B,结果为Ture.NorImplemented本身不会打断程序的运行.

如果两个对象的__eq__()都不能正确得出结果,解释器会继续尝试调用两个对象的__ne__()方法,知道获取正常结果或异常.

对比NotImplementedError,NotImplementedError是一个异常类,表示类的抽象方法或者开发者定义的接口方法,没有被重写,而出现的异常,会打断程序的执行,可以被捕获.

class C:
  def interface(self):
    raise NotImplementedError('you have to overwrite this method')
复制代码

Ellipsis

  • 和省略号文字字面"..."相同,特殊值主要与用户定义的容器数据类型的扩展切片语法结合使用
  • 循环数据结构,一个符合对象包含只想自身的引用
  • 对其赋值不会抛错

该对象的布尔值为真

>>> bool(Ellipsis)
True
复制代码

示例:

>>> def func(): Ellipsis
>>> func()

>>> def func(): ...
>>> func()

# 函数的调用结果为空
复制代码

对自身的引用:

>>> array = [1, 2, 3]
>>> array.append(array)
>>> print(array)
[1, 2, 3, [...]]
复制代码

在numpy中被用来模拟数据结果:

>>> import numpy as np
>>> l = np.linspace(1, 100, num=10000


    
)
>>> print(l)
array([  1.        ,   1.00990099,   1.01980198, ...,  99.98019802,
        99.99009901, 100.        ])
复制代码

__debug__

  • 是一个bool类型的常量,对其赋值会抛出语法错误
>>> __debug__ = False
SyntaxError: assignment to keyword
复制代码
  • 如果Python没有使用-O选项启动,此常量是真值,否则是假值。

site 模块添加的常量

site 模块(在启动期间自动导入,除非给出 -S 命令行选项)将几个常量添加到内置命名空间。 它们对交互式解释器 shell 很有用,并且不应在程序中使用。

  • quit(code=None)

  • exit(code=None)

    quit()exit()表示退出python解释器

    当打印此对象时,会打印出一条消息,例如“Use quit() or Ctrl-D (i.e. EOF) to exit”,当调用此对象时,将使用指定的退出代码来引发 SystemExit

  • copyright

  • credits

    打印或调用的对象分别打印版权或作者的文本。

  • license

    当打印此对象时,会打印出一条消息“Type license() to see the full license text”,当调用此对象时,将以分页形式显示完整的许可证文本(每次显示一屏)。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/57134
 
251 次点击