【问题标题】:Python Problems with execexec 的 Python 问题
【发布时间】:2014-05-18 18:23:23
【问题描述】:

我打电话

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

在我的实体类的init方法中,加载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))

当玩家触摸到蜘蛛时,我在原始的 touch 方法中调用 touch2(entity) 来执行来自 spider.py 的 touch2 方法中的代码。 但是当我这样做时,我得到了这个错误:

NameError: name 'touch2' is not defined

有谁知道,我如何从我在 init 中加载的其他类调用该方法?

编辑:Import Lib 不起作用...有人能告诉我如何修复该错误并使用我加载的类中的方法吗?

【问题讨论】:

  • 你为什么要这样做?为什么不直接导入 - 如果需要导入具有动态名称的文件,可以使用 importlib

标签: python exec


【解决方案1】:

据我所知,您正在读取文件而不是导入文件。改变这一行

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

import spider

希望这会有所帮助:)

更新:

正如 @DanielRoseman 在 cmets 中所提到的,如果您使用 importlib 模块(我个人没有经验,所以很遗憾我帮不上忙),您应该能够使用 self.filename 而不是导入它必须使用spider

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-23
    • 2011-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-27
    相关资源
    最近更新 更多