python - 尝试调用类中的函数时出现名称错误
问题描述
我试图打印字符串中值的索引,但我继续运行到错误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")
解决方案
我想这就是你想要实现的:
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")
这正是你似乎需要的。
推荐阅读
- listagg - 在 Orcale 中使用 LISTAGG - ORA-00937:不是单组组函数
- java - RabbitMQ 错误 java.util.concurrent.TimeoutException: null
- python - 拆分python pandas Dataframe中列的内容并使用新分离的字符串列表创建一个新的Dataframe
- c++ - 应用程序在将数据上传到数据库之前关闭,Qt
- ruby-on-rails - 部署成功后active_admin登录失败
- python-3.x - 即使错误停止,Python 日志记录也会继续写入文件
- python - Python:mupdf:dict中的无效键
- javascript - 如何使用 Tailwind CSS 创建左侧固定部分和右侧可滚动部分的 div?
- node.js - NodeJS 确认提示
- javascript - 反应:试图将 index.js 连接到数据库,但它不工作