Property setter with multiple values

后端 未结 5 1151
星月不相逢
星月不相逢 2020-12-09 11:55

I have a property setter which generates a unique id by taking two strings and hashing it:

@id.setter
def id(self,value1,value2):
    self._id = sha512(value         


        
5条回答
  •  我在风中等你
    2020-12-09 12:11

    How do I pass two values to the setter?

    You can pass an iterable(tuple, list) to the setter, for example:

    class A(object):
        def __init__(self, val):
            self.idx = val
    
        @property    
        def idx(self):
            return self._idx
    
        @idx.setter
        def idx(self, val):
            try:
                value1, value2 = val
            except ValueError:
                raise ValueError("Pass an iterable with two items")
            else:
                """ This will run only if no exception was raised """
                self._idx = sha512(value1+value2)
    

    Demo:

    >>> a = A(['foo', 'bar'])     #pass a list
    >>> b = A(('spam', 'eggs'))   #pass a tuple
    >>> a.idx
    
    >>> a.idx = ('python', 'org')  #works
    >>> b.idx = ('python',)         #fails
    Traceback (most recent call last):
        ...
        raise ValueError("Pass an iterable with two items")
    ValueError: Pass an iterable with two items
    

提交回复
热议问题