【问题标题】:Python creating objects in loopPython在循环中创建对象
【发布时间】:2018-01-16 07:46:03
【问题描述】:

我知道这个问题已经发布了很多,但是我无法让我的代码工作。我有 2 个类,Main 和 PlayerLogic。我想在一个循环中创建多个 PlayerLogic 对象,但是我收到此错误“TypeError: 'module' object is not callable”

编辑:我没有提到这些类位于具有完全相同名称的不同文件中

class Main:

    import PlayerLogic


    numPlayers = int(input("How many player would you like? [excluding you]"))

    players = []
    for i in range(numPlayers):
        players.append(PlayerLogic(i))


class PlayerLogic:

    import random


    def __init__(self,name):
        self.name = str(name)

【问题讨论】:

  • PlayerLogic 在自己的文件中吗?您可能必须将其称为 players.append(PlayerLogic.PlayerLogic(i))
  • 但是你import PlayerLogic?
  • import PlayerLogic 正在导入 PlayerLogic.py。要导入课程,请尝试from PlayerLogic import PlayerLogic
  • 啊!非常感谢,已修复
  • 另外 - 不要在模块名称中使用大写字母!调用模块playerlogic 和类PlayerLogic

标签: python class loops object


【解决方案1】:

您的导入只是导入模块而不是 PlayerLogic 类。

你可以这样做:

from PlayerLogic import PlayerLogic

或者保持导入原样,然后在循环中使用:

players.append(PlayerLogic.PlayerLogic(i))

【讨论】:

    猜你喜欢
    • 2014-06-28
    • 2015-02-04
    • 2016-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多