我想为我的物理常数找个地方。
以下答案已经是一个起点: How-to import constants in many files
所以我有一个名为 constants.py 的单独文件,我将其导入到我的项目中。
现在,我想保存并访问其他信息:
生成的界面应该是:
import constants as c
print c.R
>>> 287.102
print c.R.units
>>> J/(kg K)
print c.R.doc
>>> ideal gas constant
计算应使用 c.R 来访问该值。
它基本上是一个类,其行为类似于float类 但是还有两个附加字符串:单位和文档。 如何设计?
答案 0 :(得分:4)
从类float
继承,您必须覆盖__new__
- 方法:
class Constant(float):
def __new__(cls, value, units, doc):
self = float.__new__(cls, value)
self.units = units
self.doc = doc
return self
R = Constant(287.102, "J/(kg K)", "deal gas constant")
print R, R * 2
>>> 287.102 574.204
print R.units
>>> J/(kg K)
print R.doc
>>> ideal gas constant
答案 1 :(得分:1)
我建议使用json库,它允许您以可读和可修改的格式存储常量值。
使用继承自float的@ Daniel常量类并添加自定义属性,您可以将所有常量一次加载到新的Constants
对象中。
然后,您可以将这些属性设置为 c.R 以访问该值。
完整档案:
#!/usr/bin/env python
import json
class Constant(float):
def __new__(cls, value):
self = float.__new__(cls, value["value"]) # KeyError if missing "value"
self.units = value.get("units", None)
self.doc = value.get("doc", None)
return self
class Constants():
# load the json file into a dictionary of Constant objects
def __init__(self):
with open("constants.json") as fh:
json_object = json.load(fh)
# create a new dictionary
self.constants_dict = {}
for constant in json_object.keys():
# put each Constant into it
self.constants_dict[constant] = Constant(json_object[constant])
# try to get the requested attribute
def __getattr__(self, name):
# missing keys are returned None, use self.constants_dict[name]
# if you want to raise a KeyError instead
return self.constants_dict.get(name, None)
c = Constants()
print c.R # 287.102
print c.R.doc # ideal gas constant
print c.R + 5 # 292.102
print c.F.units # C mol-1
print c.missing # None
示例constants.json:
{
"R": {
"value": 287.102,
"units": "J/(kg K)",
"doc": "ideal gas constant"
},
"F": {
"value": 96485.33,
"units": "C mol-1",
"doc": "Faraday contant"
}
}