2016-03-18 82 views
0

無論這是否是個好主意,我想知道是否可以強制某種方法接受某個輸入,例如不帶引號(「!」)的字符。示例:如何強制Python的函數接受某個輸入?

def special_print(text): 
    """Print <text> unless ! (no quotes!) is passed as argument.""" 
    if text == !: 
     print("Easter egg!") 
    else: 
     print(text) 


special_print("Hello, World"!) 
>>> Hello, World! 

special_print("!") 
>>> ! 

special_print(!) 
>>> Easter egg! 

會這樣嗎?只是好奇。

+2

除非你願意到餐桌的Python用自己的語法。 – TigerhawkT3

回答

1

這是不可能的,除非您自己構建Python源代碼。

唯一的例外是...,這相當於Python 3(不是Python 2)中的Ellipsis對象。所以,你可以這樣做:

def special_print(text): 
    """Print <text> unless ... (no quotes!) is passed as argument.""" 
    if text == ...: 
     print("Easter egg!") 
    else: 
     print(text) 

...設計在片使用,但像Python 3,你可以在任何地方使用它。

1

不可能按照您所描述的方式進行,但我猜想您希望在交互式shell中使用這種語法,否則我甚至無法想象這會如何有用。在這種情況下,使用cmd模塊編寫你自己的shell將會是一個很好的選擇。例如:

import cmd 

class SpecialPrint(cmd.Cmd): 

    def do_print(self, line): 
     print line 

    def do_exit(self, line): 
     return True 

if __name__ == '__main__': 
    SpecialPrint().cmdloop() 

運行代碼,將產生的作品如下外殼:

(Cmd) print ! 
! 
(Cmd) print anything you want 
anything you want 
(Cmd) exit 
1

你樣的要求以一種迂迴的方式不同的問題。 Python是動態類型的,所以函數將接受任何類型。您可以使用其他類型的東西類似於您想要的東西,可能使用Sentinel對象。

Sentinel = object() 

def special_print(text): 
    if text is Sentinel: 
     print("Easter egg!") 
    else: 
     print(text) 

special_print(Sentinel) 

您不能使用!字符,因爲這不是有效的變量名稱。你不必要麼使用Sentinel對象,只需使用非字符串變量

def special_print(text): 
    if isinstance(text, int): 
     print("Easter egg!") 
    else: 
     print(text) 

special_print(1) 
相關問題