Reputation: 1852
When using Python properties (setters and getters), usually following is used:
class MyClass(object):
...
@property
def my_attr(self):
...
@my_attr.setter
def my_attr(self, value):
...
However, is there any similar approach for appending / removing arrays? For example, in a bi-directional relationship between two objects, when removing object A, it would be nice to dereference the relationship to A in object B. I know that SQLAlchemy has implemeneted a similar function.
I also know that I can implement methods like
def add_element_to_some_array(element):
some_array.append(element)
element.some_parent(self)
but I would prefer to do it like "properties" in Python.. do you know some way?
Upvotes: 3
Views: 5977
Reputation: 612
The getter property will return reference to the array. You may do array operations with that. Like this
class MyClass(object):
...
@property
def my_attr(self):
...
@my_attr.setter
def my_attr(self, value):
...
m = MyClass()
m.my_attr.append(0) # <- array operations like this
Upvotes: 0
Reputation: 40884
To make your class act array-like (or dict-like), you can override __getitem__
and __setitem__
.
class HappyArray(object):
#
def __getitem__(self, key):
# We skip the real logic and only demo the effect
return 'We have an excellent %r for you!' % key
#
def __setitem__(self, key, value):
print('From now on, %r maps to %r' % (key, value))
>>> h = HappyArray()
>>> h[3]
'We have an excellent 3 for you!'
>>> h[3] = 'foo'
From now on, 3 maps to 'foo'
If you want several attributes of your object to exhibit such behavior, you need several array-like objects, one for each attribute, constructed and linked at your master object's creation time.
Upvotes: 5