两个不同函数中的变量类型不同

2024-06-28 14:54:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个函数可以打印到excel文件中。唯一的输入是文件名。代码如下:

#excelpy
import excelpy

#Tinker
from Tkinter import *
from tkSimpleDialog import *
from tkFileDialog import *

功能模式1

def Mode1(full_name):
    print full_name
    print type(full_name) 
    testwbook = excelpy.workbook(full_name) 
    testwbook.show() 
    testwbook.set_cell((1,1),'TEST1', fontColor='red') 
    testwbook.set_range(2,1,['Number','Name']) 
    m1 = testwbook.save(full_name)
    testwbook.close()
    return m1

功能模式2

def Mode2(full_name):
    print full_name
    print type(full_name) 
    testwbook = excelpy.workbook(full_name) 
    testwbook.show() 
    testwbook.set_cell((1,1),'TEST2', fontColor='red') 
    testwbook.set_range(2,1,['Number','Name']) 
    m2 = testwbook.save(full_name)
    testwbook.close()
    return m2

主要

root = Tk()
d = str(asksaveasfilename(parent=root,filetypes=[('Excel','*.xls')],title="Save report as..."))
d = d + '.xls'
d = d.replace('/','\\')
root.destroy()  

Mode1(d)
Mode2(d)

偶尔我会发现以下错误:

Traceback (most recent call last):
  File "T:\TEST\testpy.py", line 2035, in <module>
    Mode2(d)
  File ""T:\TEST\testpy.py"", line 1381, in Mode2
    print type(full_name) 
TypeError: 'str' object is not callable

知道为什么会这样吗?我怎样才能预防呢?你知道吗


Tags: namefromimport功能deftype模式root
2条回答

在您得到错误的那一行中,惟一的函数调用是对内置函数type()的调用,因此对错误消息的唯一解释是,您通过指向字符串对象的全局名称type重写了内置名称type。尝试添加

print type

之前

print type(full_name)

看起来您正在将名为type的(全局)变量设置为字符串,从而覆盖了内置的type函数。你知道吗

尝试在代码中搜索type =以查看结果。你知道吗

可以理解,当您试图调用type(字符串不能被“调用”)时,Python会抛出这个异常。你知道吗

相关问题 更多 >