How can I get slots to work with @property for the class below. I have several thousand instances of below class which is causing memory issues and so I added the slots
I created instances with data and then add location information later to the instances.
After adding slots my instance creation is not working and I am getting the following error
AttributeError: 'Host' object has no attribute '_location'
class Host(object):
__slots__ = ['data', 'location']
def __init__(self, data, location=''):
self.data = data
self.location = location
@property
def location(self):
return self._location
@location.setter
def location(self, value):
self._location = value.lower()
def __repr__(self):
if self.location == '':
self.loc = 'Not Found'
else:
self.loc = self.location
return 'Host(name={}, location={})'.format(self.name, self.loc)
__slots__
works by creating descriptors on the class that have direct access to the in-memory data structure of your instance. You are masking thelocation
descriptor with yourproperty
object, and you defined a new attribute_location
than is not in the slots.Make
_location
the slot (as that is the attribute you are actually storing):The
location
property (also a descriptor object) can then properly assign toself._location
, an attribute backed by the slot descriptor.Note that you do not need to use
self.loc
in the__repr__
, just make that a local variable instead. You also are trying to use aself.name
attribute which doesn't exist; it is not clear what value that is supposed to be however: