Skip to main content
 首页 » 编程设计

python之为什么我在类上得到一个 AttributeError,即使我用那个名字定义了一个方法

2024年10月25日11softidea

我正在学习“面向对象编程入门”类(class),并且正在学习 Think Python 的第 17 章。下面的代码难倒了我。我在运行它时不断收到“AttributeError: 'Time' object has no attribute '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 

这些行将 hour、minute 和 second 属性添加到 start。

print_time(start) 

这会调用 print_time 并将 start 作为参数,从而产生输出:

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 function 完全分开,尽管它具有相同的名称和代码)。

在这一点上意识到这一点很重要,因为您已经创建了一个名为 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