Python中的str is not callable问题分析

来源:互联网 发布:deandre ayton体测数据 编辑:程序博客网 时间:2024/05/21 17:44

问题提出:

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

  

0 0
原创粉丝点击