我正在开发一个Python模块,它充当一种旧的游戏内脚本语言的解释器。我发现我需要很多变量,我的模块顶部如下所示:
from mufdatatypes import *
debugline=0
code=[]
debugline=0 #Line where something interesting starts
currentline=0 #Line where we currently are
infunc=0 #Need to know if we're in a function or not.
iflevel=0 #Need to track how far into ifs we are
inelse=0 #If we're in an if, have we already done an else?
looplevel=0 #Also need to know how many loops deep we're in
instrnum=0
charnum=0
gvarlist=[ "me": mufvariable(dbref(2)) , "loc" : mufvariable(dbref(0)) , "trigger" : mufvariable(dbref(-1)) , "command": mufvariable("") ]
item=''
structstack=[]
这真是乱七八糟。在执行大部分定义的函数的开头,它看起来是这样的:
def mufcompile(rawcode, primstable):
"""Compiles a source string into a list of instructions"""
global source
global code
global debugline
global currentline
global code #The actual instructions will be stored here.
global infunc #Need to know if we're in a function or not.
global iflevel #Need to track how far into ifs we are.
global inelse #If we're in an if, have we already done an else?
global looplevel #Also need to know how man loops deep we're in.
global addresstable #This will hold a table of function addresses.
global structstack #This list stack will be used to hold status info as we go further down complex statements
global instrnum #Number of instruction. Important for moving the EIP.
global vartable #Table of variables. Dictionary.
global charnum #Character in the line we're at.
global item
我有一种感觉,我这样做是不正确的,也许,有趣的人谁真正知道他们在做什么与Python。我知道变量可以当场声明,但如果我正在编写的函数上面有任何函数引用这些变量,它们就不会编译,对吗?我也有点担心全球化的程度。导入此模块的模块是否可以访问这些变量?我不想让他们这么做。你知道吗
最好制作一个字典或一个类来存储不同变量的值,至少如果它们是相关的。然后将这个对象作为参数传递给函数,就可以去掉全局变量。无论如何,您可以检查this question来了解更多关于
global
关键字的工作原理。你知道吗请记住,如果需要更改变量的全局值,则只需将变量声明为全局变量。顶层变量可以从任何地方读取/使用。你知道吗
其中一些看起来应该在一个对象中,但另一些看起来需要重新构造代码。你知道吗
应该在对象中的是
source
、lineno
等。一旦它们在对象中,您就有两个选择:要么将该对象传递给每个函数,要么更好地,使函数成为方法,以便它们可以将数据“视”为属性。你知道吗比如:
明白了吗?然后通过执行以下操作来运行代码:
但是还有其他的事情,比如
inelse
和looplevel
。这些类型的东西不应该存在于单个函数之外,您需要更多地考虑如何组织代码。很难说更多,因为我看不到所有的细节,我不想批评太多,因为这是伟大的,你正在考虑这个。。。你知道吗相关问题 更多 >
编程相关推荐