【发布时间】:2019-03-08 08:08:07
【问题描述】:
我想控制Webpage类的输入。意思是,我想确保适当地提供了网页的链接,例如'http://example.com'。
class Webpage(object):
def __init__(self, link):
prefix = ['http', 'https']
suffix = ['com', 'net']
try:
if link.split(':')[0] in prefix and link.split('.')[-1] in suffix:
self.link = link
except:
raise ValueError('Invalid link')
def get_link(self):
'''
Used to safely access self.link outside of the class
Returns: self.link
'''
return self.link
def __str__(self):
return str(self.link)
但是,当我尝试代码时:
test_link = Webpage('example.com')
如我所料,我没有收到ValueError。方法调用:
test_link.get_link()
print(test_lint)
结果
AttributeError: 'Webpage' object has no attribute 'link'
这表明 try/except 部分工作 - try 没有执行 self.link = link,但是 except 语句没有被执行。
一个例子:
test_link = Webpage('http://example.com')
适用于该类的 get_link() 和 print 方法。
将不胜感激任何提示。
【问题讨论】:
-
网址“example.com”未通过您的
if声明:if link.split(':')[0] in prefix and link.split('.')[-1] in suffix:。 -
也许您想要在
else块中引发异常?
标签: python oop try-catch init except