我想控制类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
方法一起正常工作。
将不胜感激。
答案 0 :(得分:1)
您可以使用str.startswith
和str.endswith
并在其他地方创建raise
。
演示:
class Webpage(object):
def __init__(self, link):
prefix = ('http', 'https')
suffix = ('com', 'net')
if (link.startswith(prefix)) and (link.endswith(suffix)):
self.link = link
else:
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')
print(test_link.get_link())
答案 1 :(得分:0)
在您的情况下提高期望值,在try块中完成ValueError,而在except块中完成期望的处理
有关更多信息,请访问Raising Expections in python
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
else:
raise ValueError('Invalid link')
except ValueError as exp:
print("the value error is {}\nthe link specified is {} ".format(exp,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')
输出
the value error is Invalid link
the link specified is example.com
希望这会有所帮助
答案 2 :(得分:0)
try:
if link.split(':')[0] in prefix and link.split('.')[-1] in suffix:
self.link = link
except:
raise ValueError('Invalid link')
如果传递链接example.com
,则if语句失败,因为它不包含任何前面提到的前缀。由于其逻辑上正确,因此它将永远不会下降到except
块。
您可能需要检查self.link
函数中是否存在get_link
答案 3 :(得分:0)
尝试此更新的代码
class Webpage(object):
def __init__(self, link):
prefix = ['http', 'https']
suffix = ['com', 'net']
if link.split(':')[0] in prefix and link.split('.')[-1] in suffix:
self.link = link
else:
self.link = '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')
test_link.get_link()
print(test_link)