我正在学习“面向对象编程入门”类(class),正在学习 Think Python 的第 17 章。下面的代码难倒了我。运行时,我不断收到“AttributeError:'Time'对象没有属性'print_time'”,但我很难弄清楚它。有人可以帮助我分解我做错的事情并帮助我更好地解释它吗?
class Time(object):
"""represents the time of day. attributes: hour, minute, second"""
def print_time(time):
print '%.2d:%.2d:%.2d' % (time.hour, time.minute, time.second)
start = Time()
start.hour = 9
start.minute = 45
start.second = 00
print_time(start)
class Time(object):
def print_time(time):
print '%.2d:%.2d:%.2d' % (time.hour, time.minute, time.second)
start.print_time()
我读到这是一个缩进错误,但我设置了 IDLE 来警告我是否存在冲突,并检查了两次但无济于事。
最佳答案
让我们一次(咳嗽)一步地浏览一下您的代码。
class Time(object):
"""represents the time of day. attributes: hour, minute, second"""
在这里,您定义了 class 时间
。它有一个 docstring ,但没有方法或其他属性。
def print_time(time):
print '%.2d:%.2d:%.2d' % (time.hour, time.minute, time.second)
这是一个function ,与您之前定义的 Time
类完全分开,该类接受参数 time
并尝试使用 time
的 打印字符串小时
、分钟
和秒
属性。如果 time
不具备所有这些属性,您将收到错误消息。
start = Time()
这将创建一个名为 start
的 Time
对象。
start.hour = 9
start.minute = 45
start.second = 00
这些行将小时
、分钟
和秒
属性添加到start
。
print_time(start)
这会以 start
作为参数调用 print_time
,从而产生输出:
09:45:00
到目前为止一切顺利。现在...
class Time(object):
def print_time(time):
print '%.2d:%.2d:%.2d' % (time.hour, time.minute, time.second)
这会创建一个新类,它也被称为Time
。这次它没有文档字符串,但它确实有 method称为 print_time
(它与之前定义的 print_time
函数 完全分开,尽管它具有相同的名称和代码)。
此时必须认识到,仅仅因为您创建了一个名为 Time
的新类,它根本不会对您创建的对象产生任何影响与之前定义的类。它们仍然是您定义的原始 Time
类的实例。使用内置的 help
函数很容易证明这一点:
>>> help(start)
Help on Time in module __main__ object:
class Time(__builtin__.object)
| represents the time of day. attributes: hour, minute, second
|
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables (if defined)
|
| __weakref__
| list of weak references to the object (if defined)
start.print_time()
请注意,help
显示了原始 Time
类中的文档字符串,但不显示新版本中的方法。
>>> help(Time)
Help on class Time in module __main__:
class Time(__builtin__.object)
| Methods defined here:
|
| print_time(time)
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables (if defined)
|
| __weakref__
| list of weak references to the object (if defined)
...而这显示了新 Time
类中的 print_time
方法,而不是原始类中的文档字符串。
一种思考方式是,类就像一个制造物体的工厂 - 拆除福特工厂,然后在同一个地方 build 一个新工厂,不会对已经坐在那里的 71 野马产生任何影响你的车道。
如果您想要 new Time
类的实例,则必须创建它:
>>> restart = Time()
...然后,一旦它具有正确的属性...
>>> restart.hour = 9
>>> restart.minute = 45
>>> restart.second = 00
...您将能够成功调用其 print_time
方法:
>>> restart.print_time()
09:45:00
关于python - 即使我定义了一个具有该名称的方法,为什么我会在类上收到 AttributeError 错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28811167/