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