如何通过"Duck Typing"来区分元组和简单字符串?

Phi*_*hil 3 python python-2.7

我对编程比较陌生,所以请原谅,如果我将下面的内容称为Duck Typing,那就是犯了一个荒谬的错误.

我有一个过程接收字符串元组(包含字符串)作为单个参数.

例:

def proc(arg):
    try:
        arg is a tuple
        handle arg a tuple
    except:
        arg is a simple string
        handle it so
Run Code Online (Sandbox Code Playgroud)

根据参数是否为元组,我希望函数的行为不同.

我不想键入check并想使用try..except进程.

我想过尝试arg[0]但是Python中的字符串也是对象,在这方面它们的行为就像元组并返回一些东西.

我能在这做什么?

谢谢.

Inb*_*ose 5

在你的情况下,我建议你不要尝试..除了你想要根据变量的类型表现不同...

当你的行为不同时,你应该使用try..except.

从我的评论:

当代码期望事物始终以相同的方式起作用时,您应该使用异常.在这里,你希望代码的行为取决于变量,所以你不应该尝试.except,而是检查它是什么

你可以用isinstance.

isinstance(x, tuple)
Run Code Online (Sandbox Code Playgroud)

请参阅这篇文章之间的差额isinstance,并type

所有关于鸭子打字和宽恕


使用您的代码和我的答案来创建解决方案:

def proc(arg):
    if isinstance(arg, tuple):
        # handle as tuple
    elif isinstance(arg, str):
        # handle as str
    else:
        # unhandled?
Run Code Online (Sandbox Code Playgroud)

  • 你好.我也考虑过isinstance但是不是**类型检查**不鼓励吗? (2认同)