具有多个值的属性设置器

具有多个值的属性设置器,第1张

具有多个值的属性设置

如何将两个值传递给设置器?

您可以将iterable(元组,列表)传递给setter,例如:

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)

演示:

>>> a = A(['foo', 'bar'])     #pass a list>>> b = A(('spam', 'eggs'))   #pass a tuple>>> a.idx<sha512 HASH object @ 0xa57e688>>>> a.idx = ('python', 'org')  #works>>> b.idx = ('python',)         #failsTraceback (most recent call last):    ...    raise ValueError("Pass an iterable with two items")ValueError: Pass an iterable with two items


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5646073.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存