类型检查与“重载”Python构造函数中的Duck类型

类型检查与“重载”Python构造函数中的Duck类型,python,variadic-functions,typechecking,duck-typing,Python,Variadic Functions,Typechecking,Duck Typing,我希望有一个Python类,它的实例可以以多种方式构建 我在SO中读到了一些关于python中duck类型的答案,但由于我的参数将是序列和字符串的某种组合,所以我根本不确定我是以python的方式做事的 我想处理: 单个可拆分字符串; 一个参数的单个数字或字符串序列; 由字符串或数字组成的可变长度参数列表; 大多数人仍然怀疑: 需要区分单个字符串和单个序列,因为字符串可以像序列一样工作; try与if的使用与否。 使用try与手动引发异常。 以下是我目前的代码,它适用于一些到目前为止的初始用例:

我希望有一个Python类,它的实例可以以多种方式构建

我在SO中读到了一些关于python中duck类型的答案,但由于我的参数将是序列和字符串的某种组合,所以我根本不确定我是以python的方式做事的

我想处理:

单个可拆分字符串; 一个参数的单个数字或字符串序列; 由字符串或数字组成的可变长度参数列表; 大多数人仍然怀疑:

需要区分单个字符串和单个序列,因为字符串可以像序列一样工作; try与if的使用与否。 使用try与手动引发异常。 以下是我目前的代码,它适用于一些到目前为止的初始用例:

#!/usr/bin/env python
# coding: utf-8

import re

class HorizontalPosition(object):
    """
    Represents a geographic position defined by Latitude and Longitude

    Arguments can be:
        - string with two numeric values separated by ';' or ',' followed by blank space;
        - a sequence of strings or numbers with the two first values being 'lat' and 'lon';
    """

    def __init__(self, *args):

        if len(args) == 2:
            self.latitude, self.longitude = map(float, args)

        elif len(args) == 1:
            arg = args[0]

            if isinstance(arg, basestring):
                self.latitude, self.longitude = map(float, re.split('[,;]?\s*', arg.strip()))

            elif len(arg) == 2:
                self.latitude, self.longitude = map(float, arg)

        else:
            raise ValueError("HorizontalPosition constructor should receive exactly one (tuple / string) or two arguments (float / string)")


    def __str__(self):
        return "<HorizontalPosition (%.2f, %.2f)>" % (self.latitude, self.longitude)


    def __iter__(self):
        yield self.latitude
        yield self.longitude


if __name__ == "__main__":
    print HorizontalPosition(-30,-51)       # two float arguments
    print HorizontalPosition((-30,-51))     # one two-sized tuple of floats
    print HorizontalPosition('-30.0,-51')   # comma-separated string
    print HorizontalPosition('-30.0 -51')   # space-separated string

    for coord in HorizontalPosition(-30, -51):
        print coord

称之为水平位置似乎很奇怪。这让它听起来像只有一个维度。我根本不会给这个多个构建选项。字符串构造函数听起来像是将构造函数与程序的输入格式联系得太紧密了,而序列构造函数只能是HorizontalPosition*coords,它将coords解包并调用2参数构造函数。@user2357112关于您的最后一条评论,问题是:那么我如何实现这一点呢?。据我所知,我不能在Python中使用实际的重载。。。在HorizontalPositionlat,lon和HorizontalPositionlat,lon之间的处理应该在单个构造函数中执行,但我不知道应该如何执行,以及为什么。