下面是我创建的一个类,可以轻松地将一堆数据存储为属性。他们最终被存储在字典中。我覆盖__getattr__
并__setattr__
以不同类型的单位存储和检索值。当我开始覆盖时__setattr__
,我无法在第二行创建初始字典,__init__
就像这样......
super(MyDataFile, self).__setattr__('_data', {})
我的问题......
有没有更简单的方法来创建一个类级别的属性__setattr__
?另外,我应该担心保留单独的字典还是应该将所有内容都存储在 中self.__dict__
?
#!/usr/bin/env python
from unitconverter import convert
import re
special_attribute_re = re.compile(r'(.+)__(.+)')
class MyDataFile(object):
def __init__(self, *args, **kwargs):
super(MyDataFile, self).__init__(*args, **kwargs)
super(MyDataFile, self).__setattr__('_data', {})
#
# For attribute type access
#
def __setattr__(self, name, value):
self._data[name] = value
def __getattr__(self, name):
if name in self._data:
return self._data[name]
match = special_attribute_re.match(name)
if match:
varname, units = match.groups()
if varname in self._data:
return self.getvaras(varname, units)
raise AttributeError
#
# other methods
#
def getvaras(self, name, units):
from_val, from_units = self._data[name]
if from_units == units:
return from_val
return convert(from_val, from_units, units), units
def __str__(self):
return str(self._data)
d = MyDataFile()
print d
# set like a dictionary or an attribute
d.XYZ = 12.34, 'in'
d.ABC = 76.54, 'ft'
# get it back like a dictionary or an attribute
print d.XYZ
print d.ABC
# get conversions using getvaras or using a specially formed attribute
print d.getvaras('ABC', 'cm')
print d.XYZ__mm