Python exec 的问题

1 投票
1 回答
1230 浏览
提问于 2025-04-18 06:55

我在我的实体类的初始化方法里调用了

exec(compile(open(self.filename, "rb").read(), self.filename, 'exec'))

这个方法,它会加载 spider.py 文件:

import util, colors, random

self.dtouch = False

def touch2(self, entity):
    self.level.ps.add_particle(self.get_rect().x + random.randint(0, 31), self.get_rect().y + random.randint(0, 31), 0, -5, 2, 2, colors.RED, 500 + random.randint(0, 50))

当玩家碰到这个蜘蛛时,我在原来的触碰方法里调用了 touch2(entity),目的是执行 spider.py 中 touch2 方法里的代码。

但是这样做的时候,我遇到了这个错误:

NameError: name 'touch2' is not defined

有没有人知道,我该怎么从我在初始化时加载的另一个类里调用这个方法呢?

补充:导入库的方法不管用……有人能告诉我怎么解决这个错误,并且使用我加载的那个类里的方法吗?

1 个回答

0

从我看到的情况来看,你是在读取文件,而不是导入它。把这一行

exec(compile(open(self.filename, "rb").read(), self.filename, 'exec'))

改成

import spider

希望这能帮到你 :)

更新:

正如@DanielRoseman在评论中提到的,如果你使用importlib模块(我个人没有这方面的经验,所以帮不了你),你应该可以用self.filename来导入,而不需要用spider

撰写回答