程序显示小时,分钟和秒

时间:2014-08-11 08:18:31

标签: python

我有一个简单的程序打印小时,分钟和秒。但是,在第6行中,错误消息显示类Time()未定义。我想知道为什么?

class Time(object):

    def print_time(time):
        print('%.2d:%.2d:%.2d' % (time.hour, time.minute, time.second))

    start = Time() #assign class Time to variable start

    start.hour = 9
    start.minute = 45
    start.second = 00

    Time.print_time(start) #classname.methodname(parameter)

第6行显示错误消息,未定义类Time:

  File "C:\Program Files (x86)\Wing IDE 101 5.0\src\debug\tserver\_sandbox.py", line 1, in <module>
    # Used internally for debug sandbox under external interpreter
  File "C:\Program Files (x86)\Wing IDE 101 5.0\src\debug\tserver\_sandbox.py", line 6, in Time
builtins.NameError: name 'Time' is not defined

2 个答案:

答案 0 :(得分:2)

你的缩进是错误的。它应该是:

class Time(object):

    def print_time(time):
        print('%.2d:%.2d:%.2d' % (time.hour, time.minute, time.second))

start = Time() #assign class Time to variable start

start.hour = 9
start.minute = 45
start.second = 00

Time.print_time(start) #classname.methodname(parameter)

否则定义start的代码执行,而定义Time类本身。

答案 1 :(得分:0)

虽然其他人指出了您的问题,但我建议您使用Arrow并简单地说:

arrow.utcnow().format('HH:mm:ss')

在导入之前需要pip install arrow