python 模块变量问题

Jave.Lin 2013-08-09 02:43:43

#encoding="utf-8"

import MySQLdb
import types

# vars
# mysql connection
con = None
# connectin's cursor
cursor = None
# fetch from mysql data table
fData = None

# need to handle content
def action():
conn = MySQLdb.connect(host='localhost', user='root', passwd='...', db='testDB', port=8001, charset='gbk')
cursor = conn.cursor(cursorclass=MySQLdb.cursors.DictCursor)
cursor.execute("select * from t_award_info limit 2");
fData = cursor.fetchall();
print getXmlName() + " fetach result : "
print fData

# special output xml file name
def getXmlName():
return "AwardCfg"

# xml file content str
def getXmlStr():
return "test"

# dispose res
def dispose():
print "cursor = ", cursor # cursor = None
cursor.close()
con.close()


先执行
action()
再执行
dispose()

发现dispose里的cursor = None
咋回事
...全文
162 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
Jave.Lin 2013-08-09
  • 打赏
  • 举报
回复
忘记贴解决后的源代码:

#encoding="utf-8"

import MySQLdb
import types

#刚刚这里的变量都删除了

# need to handle content
def action():
	global conn #注要这里写上global声明,而注意的是,global这里声明后,不能直接同行赋值,要换行,语法规定?
	conn = MySQLdb.connect(host='localhost', user='root', passwd='...', db='testDB', port=8001, charset='gbk')
	global cursor
	cursor = conn.cursor(cursorclass=MySQLdb.cursors.DictCursor)
	cursor.execute("select * from t_award_info limit 2");
	global fData
	fData = cursor.fetchall();
	print getXmlName() + " fetach result : "
	print fData
	
# special output xml file name
def getXmlName():
	return "AwardCfg"
	
# xml file content str
def getXmlStr():
	return "test"

# dispose res
def dispose():
	print "cursor = ", cursor # 这会这里就不会空了
	cursor.close()
	print "conn = ", conn
	conn.close()
Jave.Lin 2013-08-09
  • 打赏
  • 举报
回复
OK,自己解决了: 感觉这py的全局变量写法好奇葩 这样: 那些不在方法内声明的global变量 或是 内方法声明的global变量 在一个方法里就不好分了,除自己变量名为:g_XXX开头还比较好
Jave.Lin 2013-08-09
  • 打赏
  • 举报
回复
难道说python的模块变量,在各方法之间不能通用?还是少了什么送键这?
# vars
# mysql connection
con = None
# connectin's cursor
cursor = None
# fetch from mysql data table
fData = None
这少变量 我加了global一样不行

37,719

社区成员

发帖
与我相关
我的任务
社区描述
JavaScript,VBScript,AngleScript,ActionScript,Shell,Perl,Ruby,Lua,Tcl,Scala,MaxScript 等脚本语言交流。
社区管理员
  • 脚本语言(Perl/Python)社区
  • IT.BOB
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧