arthas_dk
arthas_dk

Reputation: 443

Use of arguments with property.deleter

I'm trying to define a property deleter with a parameter for an attribute of Character class as follows:

class Character(object):
    _status = None

    @property
    def status(self):
        """ Return _status if it exists or False if not."""
        return self._status

    @status.setter
    def status(self, status_value):
        """
        Receive the status and the duration(continous or not) and add
        it for the _status.
        """
        if not self._status:
            self._status = []

        self._status.append(status_value)

    @status.deleter
    def status(self, status_value):
        """
        Delete the specified object from the _status list.
        """
        status = [value for value in self._status
                  if status_value in value.keys()]
        if status:
            self._status.remove(self._status.index(status[0]))

I'm trying to delete a specific object from the status.

>>>a = Character()
>>>a.status = 'Test'

Would return a list with 1 element:

>>>a.status
['Test']

If i set the status again, the old value persists and new one is added to the list:

>>>a.status = 'Dazed'
>>>a.status
['Test', 'Dazed']

As well I want to delete only a specific value from the list:

>>>del a.status('Dazed')

And the expected result should be:

>>> a.status
['Test']

The problem is that hen I try:

del a.status('Dazed')

The following error occurs:

SyntaxError: can't delete function call

Is there any way to use arguments with a property.deleter?

Upvotes: 0

Views: 699

Answers (1)

jonrsharpe
jonrsharpe

Reputation: 122107

This is odd behaviour you are trying to create, and would likely trip up users of your class. I certainly wouldn't expect:

self.status = "happy"

to add the new string to an existing list.

As far as I'm aware there is no way to pass an argument to a @property.deleter.

A better approach might be to make the character.status a set (I am assuming that you meant this to be an instance attribute, but this all stands for class attributes too):

class Character(object):

    def __init__(self, ..., status=None):
        if status is None:
            self.status = set()
        else:
            self.status = set(status)
        ...

conan = Character(..., status=("happy", "cold"))

conan.status.add("tired")

conan.status.remove("happy")

One advantage of a set is that it prevents duplicates. Also, it provides for very fast membership tests (e.g. if "warm" in conan.status:) and you can find out if two Character instances have any of the same status easily:

if conan.status.intersection(other_character.status):

Upvotes: 2

Related Questions