class BadStar(Exception): pass
class Star(object):
def __init__(self, name, mass, mag, color, x, y, z):
self.name = name
self.mass = float(mass)
self.mag = float(mag)
self.color = color
self.pos = (float(x),float(y),float(z))
@classmethod
def fromstr(cls, s):
"Alternate constructor from string"
stardata = [i.strip() for i in s.split(',')]
if len(stardata)==7:
return cls(*stardata)
else:
raise BadStar("wrong number of arguments in string constructor")
def __str__(self):
x,y,z = self.pos
return "{0} is at ({1}, {2}, {3})".format(self.name, x, y, z)
class StarIndex(dict):
def load(self, fname):
"Load stars from text file"
with open(fname, "r") as f:
for line in f:
line = line.split('#')[0] # discard comments
line = line.strip() # kill excess whitespace
if len(line): # anything left?
try:
star = Star.fromstr(line)
self[star.name] = star
except BadStar:
pass # discard lines that don't parse
return self
и некоторые примеры данных:
# Name, Mass, Absolute Magnitude, Color, x, y, z
#
# Mass is kg
# Color is rgb hex
# x, y, z are lightyears from earth, with +x to galactic center and +z to galactic north
Sol, 2.0e30, 4.67, 0xff88ee, 0.0, 0.0, 0.0
Alpha Centauri A, 2.2e30, 4.35, 0xfff5f1, -1.676, -1.360, -3.835
, затем вы можете загрузить свой файл следующим образом:
s = StarIndex().load("stars.txt")
и
print s["Sol"]
приводит к
Sol is at (0.0, 0.0, 0.0)