【问题标题】:OOP / try except statements in __init__ of classOOP / try except 类的 __init__ 中的语句
【发布时间】: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


【解决方案1】:

您可以使用 str.startswithstr.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())

【讨论】:

  • 嘿拉克什。如下所示,我也想用“try/except”来练习——我可以用“if/else”的方式。但是,那些str.startswithstr.endswith 非常好!谢谢,M。
【解决方案2】:

在你的情况下引发期望 ValueError 是在 try 块中完成的,而对期望的处理是在 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

希望对你有帮助

【讨论】:

  • 这正是我想要的。奇迹般有效!那个“.format(exp,link)”也可以完成这项工作。非常感谢,阿尔宾保罗。米
  • 我同意在这种情况下没有具体点。我只是在说明我们如何强制异常并使用 except 来处理它。
  • 我也是这么想的,我想这个例子根本不适合在try/except这件事上练习……
【解决方案3】:

试试这个更新的代码

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)

【讨论】:

  • 感谢 Dithon 的努力。但是,我也想用“try/except”来练习——我可以用“if/else”的方式。最好的,M
  • @mmikeel:只需将self.link = 'Invalid link' 更改为raise ValueError('Invalid link')。您可以通过将test_link = Webpage('example.com') 语句放在try/except 中来练习处理异常。
【解决方案4】:
 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 函数中

【讨论】:

    猜你喜欢
    • 2011-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-10
    • 2018-02-24
    • 1970-01-01
    • 1970-01-01
    • 2017-11-30
    相关资源
    最近更新 更多