請教大神,Python @property setter可以設置多個屬性值嗎?
例如
class A():
...
@property
def a(self,x,y): ...
@a.setter
def a(self,x,y): self.x=x; self.y=y
你可以傳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