我想要一个Python类,其实例可以通过多种方式构建。
我在SO中读到了一些关于python中鸭子输入的答案,但由于我的参数是序列和字符串的组合,我不确定我是以pythonic的方式做事。
我想处理:
大多数疑虑仍然存在:
try
vs 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