简体   繁体   English

如何为同一个功能使用不同的输入类型?

[英]How to have different input types for the same function?

The basic idea of what I want to do is: 我想做的基本想法是:

def aFuncion(string = '', dicti = {}):
    if len(str) > 0:
         print 'you gave string as input'
    if len(dicti) > 0:
         print 'you gave a dict as input'

aFunction(string = 'test')
dict['test'] = test
aFunction(dicti = dict)

I know this kind of idea is possible in more OO type of languages, but is this also possible in python? 我知道这种想法在更多OO类型的语言中是可能的,但这在python中也是可能的吗?

Right now I'm doing 现在我正在做

def aFuncion(input):
    if type(input) == str:
         print 'you gave string as input'
    if type(input) == dict:
         print 'you gave a dict as input'

aFunction('test')

But I want the difference to be clear when the function is called 但我希望在调用函数时能够清楚区别

The idea of having the same method support different argument types is known as multiple dispatch or multimethods . 使用相同方法支持不同参数类型的想法称为多个调度或多方法

To get a good introduction to it, you can read this Guido Van Rossum article and have a look at PyPi since there are a few multimethod packages available. 为了得到一个很好的介绍,你可以阅读这篇Guido Van Rossum 文章 ,看看PyPi,因为有一些多方法包可用。

This goal of wanting "the difference to be clear when the function is called" doesn't rub so well with the design philosophy of the language. 这个想要“在调用函数时要明确区别”的目标并没有与语言的设计理念相提并论。 Google "duck typing" for more information about that. 谷歌“鸭子打字”了解更多相关信息。 The accepted inputs should be made clear by the docstring of the function, and that's all you need to do. 接受的输入应该通过函数的文档字符串清楚,这就是你需要做的。

In python, when you want your input it to be a string or a dict, then you just write code which assumes the input will be an object which behaves in behave in a string-like way or a dict-like way. 在python中,当你想要输入它是一个字符串或一个字典时,那么你只需要编写代码,该代码假定输入将是一个对象,其行为类似于字符串或类似dict的方式。 If the input doesn't, then you can try to handle that gracefully if you want, but usually you can simply leave your code to simply pop with an unhandled exception. 如果输入没有,那么你可以尝试如果你想要优雅地处理它,但通常你可以简单地让代码弹出一个未处理的异常。 This puts the ball back in the caller's court to either decide how to handle the situation, or realise that they were sending in bad data. 这会将球放回呼叫者的球场,以决定如何处理这种情况,或者意识到他们正在发送不良数据。

Type checks should be avoided in general, if really necessary it should be done with isinstance rather than an equality check on the type like you have done. 通常应该避免类型检查,如果确实有必要,应该使用isinstance而不是像您所做的那样对类型进行相等检查。 This has the advantage of being more flexible for inheritance situations. 这具有对继承情况更灵活的优点。

def aFuncion(input_):
    if isinstance(input_, str):
        print 'you gave a string-like input'
    elif isinstance(input_, dict):
        print 'you gave a dict-like input'

aFunction('test')

In python3 you now have another option of using type hinting function annotations. 在python3中,您现在可以使用类型提示功能注释。 Read PEP 484 for more details about that feature. 有关该功能的更多详细信息,请阅读PEP 484

What you have basically works, there's just some trouble with the variable declarations. 你有什么基本上工作,变量声明只是一些麻烦。 Here is a working vesrion: 这是一个工作的vesrion:

def aFunction(str = '', dicti = {}):
    if len(str) > 0:
         print 'you gave string as input'
    if len(dicti) > 0:
         print 'you gave a dict as input'

str = 'test'
dicti = dict([('test', 'test')])
aFunction(str = str)
aFunction(dicti = dicti)
aFunction(str = str, dicti = dicti)
aFunction(dicti = dicti, str = str)

puts: 提出:

you gave string as input
you gave a dict as input
you gave string as input
you gave a dict as input
you gave string as input
you gave a dict as input

You can also have non-specific arguments that are sent to the function as both a list and a dictionary (see What is a clean, pythonic way to have multiple constructors in Python? for example). 您还可以将非特定参数作为列表和字典发送到函数(例如,参见什么是在Python中具有多个构造函数的干净,pythonic方式? )。

暂无
暂无

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

相关问题 如何以 python 方式处理具有相同操作的不同输入类型? - How to handle different input types with the same actions pythonically? Function 字节编码相同的输入并有不同的响应 - Function byte encode same input and have different responses 对不同类型使用相同的 function - use same function for different types 我如何创建一个函数,该函数根据在Python中输入相同输入的次数,使用户输入具有不同的结果? - How do I create a function that allows for user input to have a different outcomes based on how many times the same input was entered in Python? 如何在python 2的同一行上获取不同数据类型的多个输入? 不能使用 map() 函数,因为输入有混合数据 - How to take multiple inputs of different data types on same line in python 2? can't use map() function as input has mixed data 如何使函数接受不同类型的输入? - How can I make my function accept different types of input? Python中的一个function如何输入不同类型的参数? - How to input different types of parameter to one function in Python? 需要更改大写python以使用raw_input函数解释3种不同类型的输入SAME - Need to change capitalize python to interpret 3 different types of inputs the SAME with the raw_input function 在列表中调用不同类型的相同函数 - calling same function with different types in list 如何在同一个Eclipse项目中使用不同类型的构建器/源文件夹 - How to have builders/source-folders of different types in same eclipse project
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM