具有多个值的属性设置器 [英] Property setter with multiple values

查看:46
本文介绍了具有多个值的属性设置器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个属性设置器,它通过获取两个字符串并对其进行散列来生成一个唯一的 ID:

@id.setterdef id(self,value1,value2):self._id = sha512(value1+value2)

我有两个问题:

  1. 是否允许(考虑到良好的 Python 编码实践)以这种方式进行编码
  2. 如何将两个值传递给 setter?

解决方案

如何将两个值传递给 setter?

你可以向setter传递一个iterable(tuple, list),例如:

A 类(对象):def __init__(self, val):self.idx = val@财产def idx(self):返回 self._idx@idx.setterdef idx(self, val):尝试:值 1,值 2 = val除了值错误:raise ValueError("通过两个项目传递一个迭代")别的:""" 仅当没有引发异常时才会运行 """self._idx = sha512(value1+value2)

演示:

<预><代码>>>>a = A(['foo', 'bar']) #传递一个列表>>>b = A(('spam', 'eggs')) #传递一个元组>>>a.idx<sha512 HASH 对象@0xa57e688>>>>a.idx = ('python', 'org') #works>>>b.idx = ('python',) #fails回溯(最近一次调用最后一次):...raise ValueError("通过两个项目传递一个迭代")ValueError:通过两个项目传递一个迭代

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(value1+value2)

I have two questions:

  1. Is it allowed (considering good python coding practices) to code this way
  2. How do I pass two values to the setter?

解决方案

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
<sha512 HASH object @ 0xa57e688>
>>> 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

这篇关于具有多个值的属性设置器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆