3

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?

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I was hopeing for some more property like solution, but I guess that is not possible.. I will upvote your answer =)
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.