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

最后修改:2025-02-01 08:59:27 GMT