tynet1101 2016-12-28 04:55 采纳率: 100%
浏览 2148
已采纳

Python @property setter可以设置多个属性值吗

请教大神,Python @property setter可以设置多个属性值吗?
例如
class A():
...
@property
def a(self,x,y): ...
@a.setter
def a(self,x,y): self.x=x; self.y=y

  • 写回答

1条回答 默认 最新

  • oyljerry 2016-12-28 05:42
    关注

    你可以传tuple,list等

     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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 adb push异常 adb: error: 1409-byte write failed: Invalid argument
  • ¥15 android报错 brut.common.BrutException: could not exec (exit code = 1)
  • ¥15 nginx反向代理获取ip,java获取真实ip
  • ¥15 eda:门禁系统设计
  • ¥50 如何使用js去调用vscode-js-debugger的方法去调试网页
  • ¥15 376.1电表主站通信协议下发指令全被否认问题
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥15 复杂网络,变滞后传递熵,FDA
  • ¥20 csv格式数据集预处理及模型选择
  • ¥15 部分网页页面无法显示!