Following system colour scheme - Python 增强提案 Selected dark colour scheme - Python 增强提案 Selected light colour scheme - Python 增强提案

Python 增强提案

PEP 336 – 使 None 可调用

作者:
Andrew McClelland <eternalsquire at comcast.net>
状态:
已拒绝
类型:
标准跟踪
创建:
2004年10月28日
更新历史:


目录

摘要

None 应该是一个可调用的对象,当使用任何参数调用时,它没有副作用并返回 None

BDFL 声明

此 PEP 已被拒绝。它被认为 None 在被调用时引发错误是一个特性。该提案在明显性、清晰性、明确性和必要性的测试中都存在不足。提供的 Switch 示例很好,但可以通过简单的 lambda 定义轻松处理。请参阅 2005 年 6 月 17 日的 python-dev 讨论 [1]

动机

允许一种编程风格来选择操作,这种风格更符合 Python 语言的极简函数式编程目标。

基本原理

允许在方法表中使用 None 作为通用的无效果操作,而不是 (1) 在调用之前检查方法表条目是否为 None,或 (2) 编写一个与表中其他函数类似的参数的本地无效果方法。

语义将有效地为

class None:

    def __call__(self, *args):
        pass

使用方法

之前,检查函数表条目是否为 None

class Select:

    def a(self, input):
        print 'a'

    def b(self, input):
        print 'b'

    def c(self, input):
        print 'c'

    def __call__(self, input):
     function = { 1 : self.a,
           2 : self.b,
           3 : self.c
        }.get(input, None)
     if function:  return function(input)

之前,使用本地无效果方法

class Select:

    def a(self, input):
        print 'a'

    def b(self, input):
        print 'b'

    def c(self, input):
        print 'c'

    def nop(self, input):
     pass

    def __call__(self, input):
        return { 1 : self.a,
        2 : self.b,
        3 : self.c
        }.get(input, self.nop)(input)

之后

class Select:

    def a(self, input):
        print 'a'

    def b(self, input):
        print 'b'

    def c(self, input):
        print 'c'

    def __call__(self, input):
     return { 1 : self.a,
        2 : self.b,
        3 : self.c
        }.get(input, None)(input)

参考文献


来源: https://github.com/python/peps/blob/main/peps/pep-0336.rst

上次修改: 2023-09-09 17:39:29 GMT