创建类属性而不通过 __setattr__
下面是我创建的一个类,用于轻松地将一堆数据存储为属性。 它们最终被存储在字典中。 我重写 __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
What I have below is a class I made to easily store a bunch of data as attributes.
They wind up getting stored in a dictionary.
I override __getattr__
and __setattr__
to store and retrieve the values back in different types of units.
When I started overriding __setattr__
I was having trouble creating that initial dicionary in the 2nd line of __init__
like so...
super(MyDataFile, self).__setattr__('_data', {})
My question...
Is there an easier way to create a class level attribute with going through __setattr__
?
Also, should I be concerned about keeping a separate dictionary or should I just store everything in 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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
示例中的
__setattr__
除了将内容放入_data
而不是__dict__
中删除之外,不执行任何操作。将
__getattr__
更改为使用__dict__
。将您的值和单位存储为简单的二元组。
Your
__setattr__
in the example doesn't do anything except put things in_data
instead of__dict__
Remove it.Change your
__getattr__
to use__dict__
.Store your value and units as a simple 2-tuple.