create a class attribute without going through __setattr__
Posted
by eric.frederich
on Stack Overflow
See other posts from Stack Overflow
or by eric.frederich
Published on 2010-06-11T17:17:07Z
Indexed on
2010/06/11
17:22 UTC
Read the original article
Hit count: 220
Hello,
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
© Stack Overflow or respective owner