これにより、「文字列の長さ」機能が浮動小数点数に追加されます。オブジェクトの len() は、数値が文字列であるかのように数値の長さを返します
class mynumber(float):
def __len__(self):
return len(self.__str__())
pass
a=mynumber(13.7)
b=mynumber(13.7000001)
print len(a)
print len(b)
Python 2.7 でテスト済み。お役に立てれば
あなたのコメントに基づいて、別の答えがあります。2 つの座標ペアを取り、haversine ( Haversine Formula in Python (Bearing and Distance between two GPS points) ) 式を使用して、それらの間の距離を求めるオブジェクトを設定します。
from math import radians, cos, sin, asin, sqrt
class mypointpair(object):
def __init__(self):
self.coord=[]
pass
def add_coords(self,a,b):
self.coord.append((a,b))
def __len__(self):
return self.haversine(self.coord[0][0], self.coord[0][1], self.coord[1][0], self.coord[1][1])
def haversine(self,lon1, lat1, lon2, lat2):
"""
Calculate the great circle distance between two points
on the earth (specified in decimal degrees)
"""
# convert decimal degrees to radians
lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])
# haversine formula
dlon = lon2 - lon1
dlat = lat2 - lat1
a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2
c = 2 * asin(sqrt(a))
km = 6367 * c
return km
pp1=mypointpair()
pp1.add_coords(53.32055555555556 , -1.7297222222222221 )
pp1.add_coords(53.31861111111111, -1.6997222222222223 )
print len(pp1)