如何为同一个函数设置不同的输入类型?

发布于 2025-01-05 00:31:02 字数 582 浏览 1 评论 0原文

我想做的基本想法是:

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

我知道这种想法在更多 OO 类型的语言中是可能的,但这在 Python 中也可能吗?

现在我正在做

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

aFunction('test')

但是我希望在调用函数时能够清楚地了解差异。

The basic idea of what I want to do is:

def aFunction(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?

Right now I'm doing

def aFunction(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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

甜嗑 2025-01-12 00:31:02

让相同的方法支持不同的参数类型的想法被称为多重调度或多方法

要获得对其的详细介绍,您可以阅读这篇 Guido Van Rossum 文章 并查看 PyPi,因为那里有一些多方法包可用。

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.

神也荒唐 2025-01-12 00:31:02

在 Python 中应避免类型检查(搜索“ducktyping” )。当它们必要时,通常应该使用isinstance来完成,而不是像问题所示的那样对类型进行相等检查。这样做的优点是对于继承情况更加灵活。

Python 3.4 开始,类似字符串的分支和类似字典的分支可以写成使用 stdlib functools.singledispatch

因此,

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

您现在可以:

from functools import singledispatch

@singledispatch
def aFunction(input_):
    pass

@aFunction.register(str)
def _(input_):
    print("you gave a string-like input")

@aFunction.register(dict)
def _(input_):
    print("you gave a dict-like input")

在 Python 3.5+ 中,您可以选择使用类型提示函数注释。阅读PEP 484 - 类型提示了解更多信息有关该功能的详细信息。这意味着单一调度 泛型函数 可以写成:

from functools import singledispatch

@singledispatch
def aFunction(input_):
    pass

@aFunction.register
def _(input_: str):
    print("you gave a string-like input")

@aFunction.register
def _(input_: dict):
    print("you gave a dict-like input")

Type checks should be avoided in Python (search about "duck typing" on that). When they are necessary, it should usually be done with isinstance rather than an equality check on the type like the question shows. This has the advantage of being more flexible for inheritance situations.

Since Python 3.4, the string-like branch and the dict-like branch can be written in separate functions using stdlib functools.singledispatch.

So instead of:

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

You can now have:

from functools import singledispatch

@singledispatch
def aFunction(input_):
    pass

@aFunction.register(str)
def _(input_):
    print("you gave a string-like input")

@aFunction.register(dict)
def _(input_):
    print("you gave a dict-like input")

In Python 3.5+ you have another option of using type hinting function annotations. Read PEP 484 - Type Hints for more details about that feature. It means the single dispatch generic function above can be written as:

from functools import singledispatch

@singledispatch
def aFunction(input_):
    pass

@aFunction.register
def _(input_: str):
    print("you gave a string-like input")

@aFunction.register
def _(input_: dict):
    print("you gave a dict-like input")
当爱已成负担 2025-01-12 00:31:02

你所拥有的基本上是有效的,只是变量声明存在一些问题。这是一个有效的版本:

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)

put:

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

您还可以将非特定参数作为列表和字典发送到函数(请参阅 什么是在 Python 中拥有多个构造函数的干净、Pythonic 方法? 例如)。

What you have basically works, there's just some trouble with the variable declarations. Here is a working 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).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文