我正在学习 @property 装饰器,我试图在一个毫无意义的程序中使用它们,如下所示:
class DupError(Exception):
pass
class Test:
list_test = []
def __init__(self, attribute):
try:
self._attribute = attribute
except DupError as e:
msg = ' '.join(e.args)
message = f'{e.__class__.__name__}: {msg}'
print(message)
Test.list_test.append(self)
@property
def attribute(self):
return self._attribute
@attribute.setter
def attribute(self, x):
for value in Test.list_test:
if value.user_name == x:
raise DupError('Caught an error!')
self._attribute = x
t1 = Test('g')
t2 = Test('h')
# trying to throw error
t3 = Test('g')
如您所见,我试图让程序在属性匹配时抛出 DupError。由于某种原因它不起作用。 DupError 需要在属性设置器中引发,并且 try except 块需要位于 init 构造函数中。任何人都知道我做错了什么。欢迎指正和解释
我能够让它工作如下:
class DupError(Exception):
pass
class Test:
list_test = []
def __init__(self, attribute):
try:
self._attribute = attribute
self.attribute = attribute
except DupError as e:
msg = ' '.join(e.args)
message = f'{e.__class__.__name__}: {msg}'
print(message)
Test.list_test.append(self)
@property
def attribute(self):
return self._attribute
@attribute.setter
def attribute(self, x):
for value in Test.list_test:
if value.user_name == x:
raise DupError('Caught an error!')
self._attribute = x
t1 = Test('g')
t2 = Test('h')
# trying to throw error
t3 = Test('g')
如你所见,我添加了 self.attribute = attribute 行,但是我认为这有点绕过了整个 _attribute 事情
定义属性后,您不应再在其他任何地方直接访问底层属性(在您的情况下是
_attribute
),包括__init__
方法,以便可以通过setter方法完成_attribute
的初始化attribute
以及:
def __init__(self, attribute):
try:
self.attribute = attribute
except DupError as e:
...