Reputation: 15
In my code, I have a data store with multiple variables set to instances of a class similar to that below. (The reason is that this Interval
class has lots of operator overriding functions).
class Interval(object):
def __init__(self, value):
self.value = value
data_store.a = Interval(1)
I want any references to data_store.a
to return self.value
rather than the Interval
instance. Is this possible?
Upvotes: 0
Views: 45
Reputation: 122153
As an alternative to Malik's answer, you could make a
a @property
, the Pythonic equivalent of get
and set
for managing access to internal attributes:
class DataStore(object):
def __init__(self):
self.a = Interval(1)
@property
def a(self):
return self._a.value
@a.setter
def a(self, value):
self._a = value
Here _a
is a private-by-convention attribute that stores the Interval
instance. This works as you want it:
>>> store = DataStore()
>>> store.a
1
Upvotes: 1
Reputation: 16721
You need to extend your data store whose attribute is an interval object:
class DataStore(object):
def __init__(self):
self.a = Interval(1)
def __getattribute__(self, attr):
if attr == 'a':
return object.__getattribute__(self, 'a').value
if attr != 'a':
return object.__getattribute__(self, attr)
Upvotes: 0