【发布时间】:2014-09-19 16:55:31
【问题描述】:
我在将类实例传递给另一个模块中的函数时遇到问题。
代码如下:
(在“基础”模块中):
from physics import *
...
class CellsArray(blist):
def getCollidingCells(self, cell):
diff = ((0,1), (1,0), (1,1), (0,-1), (-1,0), (-1,-1), (-1, 1), (1, -1))
result = []
for x, y in diff:
c = self.getCellByCoords(cell.x + x, cell.y + y)
if c:
result.append(c)
if result:
return result
else:
return None
def getCellByCoords(self, x, y):
for c in self:
if c.x == x and c.y == y:
return c
return None
def getCellById(self, uid):
for c in self:
if id(c) == uid:
return c
return None
class World():
def __init__(self, ...):
self.cells = CellsArray([])
...
self.procedures = [freeFallAccel, airEffects, specialProcedures,
moveCells, collisionsTest]
...
def step(self):
if not self.paused:
for f in self.procedures:
f(self.cells) #here the collisionsTest function is being called
(在“物理”模块中):
import base
...
def collisionsTest(cells):
for c in cells:
cells.getCollidingCells(cells.getCellByCoords(c.x, c.y))
当我将“基础”模块加载到交互式解释器中(或在“基础”模块中创建 CellsArray 实例)时,一切似乎都很好:
(交互式解释器示例):
>>> a = CellsArray([])
>>> a.append(Cell())
>>> a.getCollidingCells(a[0])
#returns None
>>> a.getCollidingCells
<bound method CellsArray.getCollidingCells of blist([<__main__.Cell instance at 0x7f847e8fa170>])>
但是当physics.collisionsTest在“基础”模块内的某处执行时,会发生错误:
cells.getCollidingCells(cells.getCellByCoords(c.x, c.y))
AttributeError: 'list' object has no attribute 'getCollidingCells'
但是,如果我将 print type(cells); print cells.getCollidingCells 添加到 collisionsTest 函数(在 for c in cells ... 之前),它会返回:
<class 'base.CellsArray'>
<bound method CellsArray.getCollidingCells of blist([<base.Cell instance at 0x7f2e4a7d1638>, ...])>
我觉得导入“物理”模块有问题,但我已经尝试了几乎所有可用的导入该模块的方法,但我仍然收到该错误。
模块“physics”使用模块“base”中的一些变量和类,所以我不能简单地删除“import base”。
有没有办法解决这个问题,或者我必须将所有函数和常量从“物理”移回“基础”?
【问题讨论】:
-
请提供一个简短、完整的程序来演示错误。请参阅stackoverflow.com/help/mcve 或SSCCE.org 了解更多信息
-
大概在
cells.getCollidingCells(cells.getCellByCoords(c.x, c.y))这行,cells是一个列表,而不是一个CellsArray。如果您需要更多调试帮助,您必须向我们展示collisionTest的调用位置。 -
CellsArray本身就是一个列表。它扩展了blist类,后者扩展了基础 Pythonlist类。blist存储在外部的第三方 Python 库中。
标签: python class inheritance import module