模仿方法重载是Pythonic吗?

hwi*_*ers 8 python

模仿静态类型语言中的方法重载是pythonic吗?我的意思是编写一个函数来检查其参数的类型,并根据这些类型的不同行为.

这是一个例子:

class EmployeeCollection(object):
    @staticmethod
    def find(value):
        if isinstance(value, str):
            #find employee by name and return
        elif isinstance(value, int):
            #find employee by employee number and return
        else:
            raise TypeError()
Run Code Online (Sandbox Code Playgroud)

Ign*_*ams 13

事实并非如此,因为你失去了使用不那么接近但足够接近的类型的能力.改为创建两个单独的方法(find_by_name()find_by_number()).

  • 如果您有5个参数可以是字符串或数字,那么您会遇到更大的体系结构问题(可能还有一个更深层次的基础问题,没有任何软件开发论坛可以帮助...). (3认同)

Ale*_*lli 13

如果所有检查都依赖于新的抽象基类,那么可能不是非常Pythonic,除了 2.6或更好之外,这些新的抽象基类部分准确地用于促进这种使用.如果你发现自己在为具体课程进行类型检查,那么你就会知道你的代码很脆弱并且限制了它的使用.

因此,例如,检查如果你有一个实例numbers.Integral是不是太糟糕-新ABC中相当一部分存在正是缓解这样的检查.检查如果你有一个实例int是一场灾难,排除long,gmpy.mpz和bazillion其他类型类似于整数数字,绝对没有好目的:从不检查具体的类!

字符串是一个困难的案例,但基本字符串抽象类(不是新的ABCs之一)是一种可能性.或许有点过于严格,但是如果你正在使用其他的ABCs,它可能有点,有点工作,如果你真的需要.绝对不是 str - 为什么要排除unicode


Sco*_*ths 5

不,这里的类型检查不是Pythonic.如果您不喜欢多种方法,另一个选择是坚持使用一种方法,但使用多个参数:

def find(name=None, employee_number=None):
    if sum(x != None for x in (name, employee_number)) != 1:
        #raise exception - exactly one value should be passed in
    if name is not None:
        #find employee by name and return
    if employee_number is not None:
        #find employee by employee number and return
Run Code Online (Sandbox Code Playgroud)

使用时,意图与多种方法一样明显:

employee1 = x.find(name="John Smith")
employee2 = x.find(employee_number=90210)
Run Code Online (Sandbox Code Playgroud)