我想在我的 python 项目中保留一组字段名称作为别名(如 'fieldName' = 'f')。虽然我很确定最直接的方法是只保留一个命令,比如
F = {'_id' : '_id',
'tower' : 'T',
'floor' : 'F',
'pos' : 'P'
}
我想我可以写一个类,比如,
class F:
def __init__():
self._id = '_id',
self.tower = 'T',
self.floor = 'F',
self.pos = 'P'
唯一的原因是我可以使用访问数据,
get_var(f._id) 与
get_var(F['_id'])
我这样做是不是在滥用python?有什么优点或缺点吗?
这些别名将在启动时从配置文件中读取,并且不会在运行时更改。
编辑:
根据 silas 的回答,我编造了这个。与您的答案相比,为什么这会很糟糕?
class Aliases:
""" Class to handle aliases for Mongo fields.
TODO: Should these be read off from a config file?
"""
def __init__(self):
self._F = {
'_id' : '_id',
'tower' : 'T',
'floor' : 'F',
'pos' : 'P',
'stabAmplitude' : 's',
'totalEnergy' : 'z',
...
}
def __getattr__(self, name):
""" Return the attributes from the alias dictionary instead of the
real attributes dictionary
"""
try:
return object.__getattribute__(self, '_F')[name]
except KeyError:
raise AttributeError('No attribute named %s.' % name)
def __setattr__(self, name, value):
""" No attributes should be changable """
if name == '_F':
return object.__setattr__(self, name, value)
else:
raise AttributeError('Attribute %s cannot be changed.', name)
请您参考如下方法:
您可能想要的(不常用的 afaik)是属性字典。
参见:https://pypi.python.org/pypi/attrdict
基本用法:
>>> from attrdict import AttrDict
>>> d = AttrDict({"id": "foo"})
>>> d.id
"foo"
如果您真的喜欢某种形式的别名属性/dict 风格的访问,那么下面的quick 'n dirty) OO 风格的代码子类attrdict .AttrDict 将起作用:
from attrdict import AttrDict
class AliasedAttrDict(AttrDict):
aliases = {}
def __getitem__(self, key):
if key in self.__class__.aliases:
return super(AliasedAttrDict, self).__getitem__(self.__class__.aliases[key])
return super(AliasedAttrDict, self).__getitem__(key)
def __getattr__(self, key):
if key in self.__class__.aliases:
return super(AliasedAttrDict, self).__getitem__(self.__class__.aliases[key])
return super(AliasedAttrDict, self).__getitem__(key)
class MyDict(AliasedAttrDict):
aliases = {
"T": "tower",
"F": "floor",
"P": "pos"
}
d = MyDict({"tower": "Babel", "floor": "Dirty", "pos": (0, 0)})
print d.tower
print d.floor
print d.pos
print d.T
print d.F
print d.P
输出:
Babel
Dirty
(0, 0)
Babel
Dirty
(0, 0)
