简体   繁体   English

如何强制Python函数接受某个输入?

[英]How to force a Python's function to accept a certain input?

Regardless of whether it's a good idea or not, I wanted to know whether it would be possible to force a method to accept a certain input, for example a character without quotes ("!"). 不管这是一个好主意,我都想知道是否有可能强制一种方法接受某个输入,例如不带引号的字符(“!”)。 Exempli gratia: 示例:

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!

Would that be possible? 那有可能吗? Just curious. 只是好奇。

This isn't possible unless you make your own build of the Python source. 除非您自己构建Python源,否则这是不可能的。

The only exception is for ... , which equates to an Ellipsis object in Python 3 (not Python 2). 唯一的例外是... ,它等于Python 3(不是Python 2)中的Ellipsis对象。 So you could do: 因此,您可以执行以下操作:

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

... is designed to be used in slices, but as of Python 3 you can use it anywhere. ...被设计用于切片,但是从Python 3开始,您可以在任何地方使用它。

No this is not possible in the way you described, but I guess that you want to use that kind of syntax in the interactive shell, otherwise I can't even imagine how this can be useful. 不,这不可能按照您描述的方式进行,但是我想您想在交互式外壳程序中使用这种语法,否则我什至无法想象这有什么用。 In this case writing your own shell with cmd module will be the way to go. 在这种情况下,使用cmd模块编写自己的shell将是可行的方法。 For example: 例如:

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()

Running of this code will spawn a shell that works as follows: 运行此代码将产生一个如下工作的shell:

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

You're kind of asking a different question in a roundabout way. 您有点以回旋处的方式提出另一个问题。 Python is dynamically typed, so a function will accept any type. Python是动态类型的,因此函数可以接受任何类型。 You can do something similar to what you want using other types, possibly using Sentinel objects. 您可以使用其他类型(可能使用Sentinel对象)执行与所需操作类似的操作。

Sentinel = object()

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

special_print(Sentinel)

You can't use a ! 您不能使用! character because that isn't a valid variable name. 字符,因为这不是有效的变量名。 You don't have to use Sentinel objects either, just use non-string variables 您也不必使用Sentinel对象,只需使用非字符串变量

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

special_print(1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM