Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/api/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 类的_init__中的OOP/try except语句_Python_Oop_Try Catch_Init_Except - Fatal编程技术网

Python 类的_init__中的OOP/try except语句

Python 类的_init__中的OOP/try except语句,python,oop,try-catch,init,except,Python,Oop,Try Catch,Init,Except,我想控制类网页的输入。也就是说,我想确保网页的链接是适当提供的,例如'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('.'

我想控制类
网页的输入。也就是说,我想确保网页的链接是适当提供的,例如
'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:“网页”对象没有属性“链接”
这表示try/except部分工作-
try
未执行
self.link=link
,但未执行
except
语句

例如:

test_link = Webpage('http://example.com')
使用该类的
get\u link()
print
方法可以正常工作


非常感谢您的任何提示。

在您的案例中提出期望值ValueError在try块中完成,期望值的处理在except块中完成

欲了解更多信息,请访问

输出

the value error is Invalid link
the link specified is example.com
希望这有帮助

 try:
            if link.split(':')[0] in prefix and link.split('.')[-1] in suffix:
                self.link = link
        except:
            raise ValueError('Invalid link') 
如果您传递link
example.com
,If语句将失败,因为它不包含任何前面提到的前缀。由于它在逻辑上是正确的,因此它将永远不会进入
块,除非
块。
您可能需要检查
self.link
是否存在于
get\u link
函数中

尝试此更新的代码

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)

您可以使用
str.startswith
str.endswith
并在else中创建
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())

url“example.com”不会传递您的
if
语句:
if-link.split(':')[0]前缀和link.split('.')[-1]后缀:
。也许您想要的是在
else
块中引发异常?这正是我想要的。工作起来很有魅力!“.format(exp,link)”也起作用。非常感谢,阿尔宾·保罗。我同意在这方面没有特别的观点。我刚才演示了如何强制异常并使用exception处理它。我也有同样的想法,我想这个示例根本不适合在try/except上进行实践……感谢Dithon的努力。然而,我想用“try/except”来练习——我可以用“if/else”的方式。最好的,M@mmikeel:只需将
self.link='Invalid link'
更改为
raisevalueerror('Invalid link')
。您可以通过将
test\u link=Webpage('example.com')
语句放在
try/except
中来练习处理异常。嘿,Rakesh。如下所示,我想用“try/except”来练习——我可以用“if/else”的方式。然而,那些
str.startswith
str.endswith
非常好!谢谢,M。
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())