【问题标题】:How to check if function is trying to access something that doesn't exist?如何检查函数是否试图访问不存在的东西?
【发布时间】:2017-03-26 16:35:12
【问题描述】:

我正在使用 python,我有这个功能:

c=15
def glteme(imgt):
    for a in range(0,80):            
        for b in range(0,80):
            if (imgt[a,b,0]==0 and imgt[a,b,1]==0 and imgt[a,b,2]==0):
                c=1
                return a,b,c

(我正在使用 80x80 的图像,在这两个 for 循环中,我正在遍历图像的每个像素并尝试找到第一个黑色像素)。所以,在这个 if condition 我正在检查图像的像素是黑色的,如果是,那么glteme(imgt) 应该返回a,b,c。然后,我尝试在代码中使用glteme(imgt)[2] 访问c

if glteme(imgt)[2]==1:
   ...

当函数返回a,b,c时,它可以访问c,但是我不知道如何检查函数是否可以访问不存在的c?(和c不存在如果在上述函数中,代码永远不会进入if 条件)我尝试了if glteme(imgt)[2]==Falseif glteme(imgt)[2] is not True 等,但它不起作用..(我收到错误'NoneType' object has no attribute '__getitem__')提前致谢!

【问题讨论】:

    标签: python return nonetype


    【解决方案1】:

    如果我正确理解您的问题,您的问题是检测图像中没有黑色像素时的情况。正如您放置函数一样,在这种情况下不会返回任何返回值。

    更改函数返回一个监护人返回值,表示没有找到黑色像素,并在返回时检查它:

    c=15
    def glteme(imgt):
        for a in range(0,80):            
            for b in range(0,80):
                if (imgt[a,b,0]==0 and imgt[a,b,1]==0 and imgt[a,b,2]==0):
                    c=1
                    return a,b,c
        return None  # This tells to the caller no result was found
    

    稍后在调用此函数时检查 None 并采取相应措施:

    res = glteme(imgt)
    
    if res is None:
        # ... no black pixel was found
    else:
        # ... do whatever with res, it will contain a, b, c
    

    【讨论】:

      【解决方案2】:

      您可以捕获这些异常,这通常比测试返回的值是否可用更好:

      try :
          a = glteme(imgt)[0]
          b = glteme(imgt)[1]
          c = glteme(imgt)[2]
          # do what you want with a,b,c
          print(a, b, c)
      except AttributeError as e:
          # this is where you don't get a,b and c
          print('no result')
      

      【讨论】:

      • @slomil 对于 a、b 和 c 来说是一样的。我已经编辑了我的答案
      【解决方案3】:

      try/except 块比 if/else 更好。 这个概念被称为“请求宽恕而不是许可”

      Python 社区使用 EAFP(请求宽恕比 许可)编码风格。这种编码风格假设需要 变量、文件等存在。任何问题都会被捕获为异常。 这导致了一种通常干净简洁的风格,其中包含很多 try 和 except 语句。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-05-12
        • 2021-09-27
        • 2018-10-01
        • 1970-01-01
        • 1970-01-01
        • 2012-03-12
        • 2022-11-29
        • 1970-01-01
        相关资源
        最近更新 更多