【发布时间】:2010-07-26 13:30:34
【问题描述】:
我目前正在尝试使用 PyGame 编写多文件 Python (2.6.5) 游戏。问题是其中一个文件“pyconsole.py”需要能够调用由主文件“main.py”导入的其他对象的实例上的方法。问题是我在主文件中有一个列表来保存所有游戏对象(玩家的船、敌船、车站等)的实例,但我似乎无法从该列表中调用方法“pyconsole.py”尽管我在主循环开始之前在“main.py”中执行了from pyconsole import *。这根本不可能吗,我是否应该使用 M4 将每个文件组合成一个单独的文件,然后进行字节码编译和测试/分发?
例子:
bash$ cat test.py
#!/usr/bin/python
import math, distancefrom00
foo = 5
class BarClass:
def __init__(self):
self.baz = 10
def get(self):
print "The BAZ is ", self.baz
def switch(self)
self.baz = 15
self.get()
bar = BarClass()
def main():
bar.switch()
print distancefrom00.calculate([2, 4])
if __name__ == '__main__': main()
bash$ cat distancefrom00.py
#!/usr/bin/python
import math
import test
def calculate(otherpoint):
return str(math.hypot(otherpoint[0], otherpoint[1]))+" (foo = "+str(test.foo)+"; "+test.bar.get()+")"
bash$ python test.py
The BAZ is 15
The BAZ is 10
Traceback (most recent call last):
File "test.py", line 24, in <module>
if __name__ == '__main__': main()
File "test.py", line 22, in main
print distancefrom00.calculate([2, 4])
File "/home/archie/Development/Python/Import Test/distancefrom00.py", line 8, in calculate
return str(math.hypot(otherpoint[0], otherpoint[1]))+" (foo = "+str(test.foo)+"; "+test.bar.get()+")"
TypeError: cannot concatenate 'str' and 'NoneType' objects
如果我对 Python 名称、类和所有这些东西的理解有限,那么 NoneType 意味着名称 test.bar.get() - 因此,test.bar - 没有分配给任何东西。
【问题讨论】:
-
“我似乎无法调用方法”是什么意思?请包含一些示例代码并提供您得到的异常。
-
啊 - 以防万一。为了您自己的安全,请不要在任何构建脚本中涉及 M4。 Python 模块可以正常工作,但您在某处遇到了错误。 M4 是邪恶的。
-
只是出于好奇,M4 怎么样(除了忘记使用
-P标志以免破坏现有文本)是邪恶的?
标签: python pygame python-import