如何显示对象的类名?

2024-04-20 09:17:24 发布

您现在位置:Python中文网/ 问答频道 /正文

请帮忙解决这个问题。我创建类和2个对象:

class Raft(object):
  def __init__(self, peoples=3, speed=10, color='maroon', sails=1):
    self.peoples = peoples
    self.speed = speed
    self.color = color
    self.sails = sails
    Raft.quantity += 1

  quantity = 0

  def __str__(self):
    # return str(self.__dict__)
    return str(self.__name__)



raft1 = Raft(peoples=2, speed=10, color='yellow', sails=1)
raft2 = Raft(peoples=3, speed=5, color='maroon', sails=0)


print(raft1)
print(raft2)

但在控制台中运行此脚本后,我收到以下错误消息:

kalinin@kalinin ~/python/boats $ python index.py
Traceback (most recent call last):
  File "index.py", line 37, in <module>
    print(raft1)
  File "index.py", line 27, in __str__
    return str(self.__name__)
AttributeError: 'Raft' object has no attribute '__name__'

我需要显示对象的类名:raft1,raft2


Tags: 对象namepyselfindexreturncolorspeed