代码之家  ›  专栏  ›  技术社区  ›  hwiechers

模仿方法重载是Pythonic吗?

  •  8
  • hwiechers  · 技术社区  · 14 年前

    模仿静态类型语言中的方法重载是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()
    
    5 回复  |  直到 13 年前
        1
  •  13
  •   Alex Martelli    14 年前

    不是很像蟒蛇, 全部的 这些检查依赖于新的抽象基类,这些抽象基类在某种程度上正是为了方便这种使用。如果你发现自己在打字 混凝土 知道 你让你的代码变得脆弱,减少了它的使用。

    例如,检查是否有 numbers.Integral int 是一场灾难,排除 long gmpy.mpz ,以及大量其他类型的整数,如数字,绝对没有什么好的用途:永远不要检查具体的类!

    字符串是一个困难的情况,但 basestring 可以 有点像工作,如果你真的需要的话。非常肯定 str unicode ?!

        2
  •  13
  •   Ignacio Vazquez-Abrams    14 年前

    find_by_name() find_by_number() )相反。

        3
  •  5
  •   Scott Griffiths    14 年前

    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
    

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

    employee1 = x.find(name="John Smith")
    employee2 = x.find(employee_number=90210)
    
        4
  •  2
  •   Scott Griffiths    14 年前

    来自python核心:

    • string.startswith() 它接受字符串或元组(字符串)。
    • string.endswith()

    在俾蒙哥:

    • find_one() 接受要查找的dict对象,或者它将使用另一个对象作为id。

    抱歉,我不知道更多,但我认为有许多方法的例子,根据给定的参数表现不同。这是不强制类型的一部分美。

        5
  •  1
  •   SingleNegationElimination    14 年前

    获得这种功能的一种更为python的方法是,尝试以首选的方式使用它(不管这意味着什么),如果这个论点不支持,那么尝试另一种方法。

    有两种方法:

    class EmployeeCollection(object):
        def find(value):
            try:
                #find employee by name and return
            catch:
                try:
                    #find employee by employee number and return
                catch:
                    raise TypeError()
    

    class EmployeeCollection(object):
        def find(value):
            if hasattr(value, 'join'):
                #find employee by name and return
            elif hasattr(value, '__div__'):
                #find employee by employee number and return
            else:
                raise TypeError()
    

    实际上,我要检查的实际属性取决于这些注释中发生了什么,我更喜欢检查我实际使用的属性。