我目前正在尝试使用 PyGame 编写多文件 Python (2.6.5) 游戏。问题是其中一个文件“pyconsole.py”需要能够调用由主文件“main.py”导入的其他对象的实例上的方法。问题是我在主文件中有一个列表来保存所有游戏对象(玩家的船、敌船、车站等)的实例,但我似乎无法从该列表中调用方法“pyconsole.py”尽管我在from pyconsole import *
主循环开始之前在“main.py”中做一个。这根本不可能吗,我是否应该使用 M4 将每个文件组合成 1 个单个文件,然后进行字节码编译和测试/分发?
例子:
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
- 没有分配给任何东西。