python - 模块在 Python 中不可调用?

标签 python

我遇到了 Python 错误。请参阅下面的代码示例。我运行 event_timer.py 并收到以下错误消息。下面列出的两个文件都在同一个文件夹中。

Traceback (most recent call last):
  File "E:\python\event_timer\event_timer.py", line 7, in 
    timer = EventTimer()
TypeError: 'module' object is not callable

What am I missing?

event_timer.py:

import EventTimer

timer = EventTimer()

timer.addStep("Preheat Oven", seconds = 10)
timer.addStep("Cook Pizza", seconds = 20)
timer.addStep("Done!")

timer.start()

事件定时器.py:

import time

class Timer:

    event = 'Event'
    steps = []

    def __init__(self, event = None):

        if event is not None:

            self.event = event

    def addStep(self, step, seconds = None, minutes = None, hours = None, days = None):

        if seconds is not None:

            unit = 'seconds'
            amount = seconds

        elif minutes is not None:

            unit = 'minutes'
            amount = minutes

        elif hours is not None:

            unit = 'hours'
            amount = hours

        elif days is not None:

            unit = 'days'
            amount = days

        else:

            print 'Invalid arguments'

            return False

        self.steps.append({'unit': unit, 'amount': amount})

        return True

    def __timeInSeconds(self, unit, amount):

        if unit == 'seconds':

            return amount

        elif unit == 'minutes':

            return amount * 60

        elif unit == 'hours':

            return amount * 60 * 60

        elif unit == 'days':

            return amount * 60 * 60 * 24

        else:

            print 'Invalid unit'

            return False

    def start(self):

        if len(self.steps) == 0:

            print 'No steps to complete'

            return False

        print "{0} has started.".format(self.event)

        for step in self.steps:

            print step.step

            time.sleep(self.__timeInSeconds(step.unit, step.amount))

            print "Completed"

        print 'Event complete'

最佳答案

当你写作时

import EventTimer

您创建了一个新变量,EventTimer,指向一个模块——您刚刚编写的模块!该模块内部是一个类 Timer。所以要创建该类的实例,您可以

timer = EventTimer.Timer()

关于python - 模块在 Python 中不可调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4259180/

相关文章:

python - 如何在 tk.Canvas 上定位形状和文本以免它们被切断?

python - 如何直接播放来自麦克风的输入数据

python - 每 x 秒执行一次 Python 而无需重新打开选项卡

python - 如何使 cStringIO 对另一个需要真实本地文件的函数透明

python - 将 numpy 数组传递给 Cython

Python:AttributeError: 'NoneType'对象没有属性 'groups'

python - 在 Python 中使用 MySQLdb 的长期陈旧结果

python - 如何在 Python 解释器中执行文件?

python - 将字符串数组中的元素输出到句子

python - SQLAlchemy:当我更新models.py中的模型时,如何更新数据库中的表