インスタンスをさまざまな方法で構築できる Python クラスが必要です。
SO で Python でのダックタイピングに関するいくつかの回答を読みましたが、引数はシーケンスと文字列の組み合わせになるため、pythonic の方法で物事を行っているかどうかはまったくわかりません。
扱いたい:
- 単一の「分割可能な」文字列。
- 数値または文字列の 1 つのシーケンス (1 つの引数)。
- 文字列または数値で構成される可変長の引数リスト。
ほとんどの疑問は次の点について残っています。
- 単一の文字列と単一のシーケンスを区別する必要があるかどうか (文字列はシーケンスとして動作する可能性があるため)。
try
vsの使用の有無if
。try
「手動で」例外を発生させる vsの使用。
これまでのところ、いくつかの初期のユースケースで機能する私の現在のコードは次のとおりです。
#!/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