首页 > 解决方案 > 尝试调用类中的函数时出现名称错误

问题描述

我试图打印字符串中值的索引,但我继续运行到错误NameError: name 'findWithException' is not defined,但我在类的正下方定义了它。这是什么原因造成的?任何帮助表示赞赏。提前致谢。

class MyString(str):
    def findWithException(s, c):
        try:
            x = s.index(c)
            print(x)
        except:
            print("Not found")
s = MyString("abcdef")
findWithException(s, "c")

标签: python

解决方案


我想这就是你想要实现的:

class MyString(str):

    def find_with_exception(self, c):
        try:
            x = self.index(c)
            print(x)
        except:
            print("Not found")


s = MyString("abcdef")
s.find_with_exception("c")

编辑,在你澄清你的问题后:

def findWithException(s, c):
    if c in s:
        x = s.index(c)
        print(x)
    else:
        print("Not found")

这正是你似乎需要的。


推荐阅读