在这里,"OK“当然意味着AYOR (由您自己承担风险),但是如果避免与现有属性名称明显的冲突,则不会出现可预见的问题。
天田天体--尤其是行星--通常具有有限的属性。我经常编写简短的脚本来提取我保存为文本并在以后使用的数字数据。这些基本上是“一次性”脚本,因为我很少使用它们超过一次或两次,从来没有分享过它们。
当我编写更持久的代码时,我肯定会创建自己的容器对象。
我的问题:似乎对我很有用,所以在这个特定的上下文中,除了属性名称的冲突之外,还有什么可能出错吗?
from skyfield.api import load
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
eph = load('de421.bsp')
earth = eph['earth']
sun = eph['sun']
ts = load.timescale()
t = ts.utc(2016, 1, np.linspace(0, 366, 1000))
# SLOPPY WAY: just add them directly
earth.pos = earth.at(t).position.km
sun.pos = sun.at(t).position.km
earth.r = np.sqrt(((earth.pos-sun.pos)**2).sum(axis=0))
earth.peri = earth.r.min()
earth.apo = earth.r.max()
print earth.peri, earth.apo, earth.pos.shape
# BETTER WAY: tedious but more cautious
uhoh = dict()
ep = earth.at(t).position.km
sp = sun.at(t).position.km
r = np.sqrt(((ep-sp)**2).sum(axis=0))
uhoh['pos'] = ep
uhoh['r'] = r
uhoh['peri'] = r.min()
uhoh['apo'] = r.max()
earth.uhoh = uhoh
print earth.uhoh['peri'], earth.uhoh['apo'], earth.uhoh['pos'].shape返回:
147100175.99 152103762.948 (3, 1000)
147100175.99 152103762.948 (3, 1000)发布于 2016-05-06 14:42:37
这确实是一种在非正式Python代码中偶尔运行的模式。除了未来的属性名称冲突之外,另一件可能出错的事情是,库作者在希望更有效地创建数百万对象的人的鼓动下,添加了一个__slots__规范,当您尝试添加其他属性时,您就会得到一个错误。
如果出现__slots__,针对它的防御措施是使用您想要使用的类的自己的子类。如果子类也没有指定__slots__ --至少表示它没有想要添加的属性--那么子类的实例是完全开放的,并且可以拥有任何属性,因此您可以始终创建自己的子类,该子类可以“解锁”实例,并允许它们具有任何属性。
请注意,像earth这样的对象有资格成为字典键,因此,如果您有一条想要与每个星球关联的信息,您可以这样说:
positions = {}
positions[earth] = ...这是一种常见的模式,当您需要记住一组对象中的每一个的额外信息时。
https://stackoverflow.com/questions/37070803
复制相似问题