网络编程
位置:首页>> 网络编程>> Python编程>> Python中str is not callable问题详解及解决办法

Python中str is not callable问题详解及解决办法

作者:lqh  发布时间:2023-10-30 05:34:42 

标签:Python,callable

Python中str is not callable问题详解及解决办法

问题提出:

   在Python的代码,在运行过程中,碰到了一个错误信息:

   python代码:


def check_province_code(province, country):
 num = len(province)

while num <3:
   province = ''.join([str(0),province])
   num = num +1

return country + province

  运行的错误信息:


check_province_code('ab', '001')
---------------------------------------------------------------------------
TypeError                 Traceback (most recent call last)
<ipython-input-44-02ec8a351cce> in <module>()
----> 1 check_province_code('ab', '001')

<ipython-input-43-12db968aa80a> in check_province_code(province, country)
  3  
  4   while num <3:
----> 5     province = ''.join([str(0),province])
  6     num = num +1
  7  

TypeError: 'str' object is not callable  

问题分析与排查:

   从错误信息分析, str不是一个可调用的对象,可是之前确实可以调用的,且在python的api文档中,其是python内置的一个函数呀, 怎么不能用了呢?

 还是继续验证一下吧。

   在命令行下执行str(123),将数字转换为string:


>>> str(1233)
---------------------------------------------------------------------------
TypeError                 Traceback (most recent call last)
<ipython-input-45-afcef5460e92> in <module>()
----> 1 str(1233)

TypeError: 'str' object is not callable

 这下问题定义清楚了,原来没有了str,仔细想了想原来刚才在定义变量的时候,随机使用str,所以就被覆盖了str函数。进行了类似以下的操作:


str = '123'

恢复默认的str函数

   重新启动一下python应用,移除str被覆盖的代码部分即可。

总结

  在python中内置了很多的函数和类,在自己定义变量的时候,切记不要覆盖或者和他们的名字重复。

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

来源:http://blog.csdn.net/blueheart20/article/details/52883045

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com