如何解决任何人都可以解释这段代码的内部处理为什么它生成输出为 [<__main__.Movie object at 0x000002DAE7122FD0>]
谁能解释下面的输出:
[<__main__.Movie object at 0x000002DAE7122FD0>]
在 while 循环中,我正在创建多个对象并存储在一个列表中,当我打印列表时,我得到的输出为 [<__main__.Movie object at 0x000002DAE7122FD0>]
。
作为,
m = Movie(title,actor,actress)
#object created 并且引用变量是 m,在下一步中将其附加到列表中。
class Movie:
def __init__(self,title,actress):
self.title = title
self.actor = actor
self.actress = actress
def info(self):
print("Movie: ",self.title)
print("Actor: ",self.actor)
print("Actress: ",self.actress)
while True:
title = input("Enter movie name")
actor = input("Enter actor name")
actress = input("Enter actress name")
movieobj = Movie(title,actress)
list_of_movies = []
list_of_movies.append(movieobj)
option = input("Do you want to add more movies? [yes/no]")
if option.lower() == 'no':
break
print(list_of_movies)
解决方法
[<__main__.Movie object at 0x000002DAE7122FD0>]
显示您有一个列表,其中包含对 Movie 对象的一个引用(以及 id
of the object,这是它在 cPython 中的内存地址,您可能正在使用)>
[<__main__.Movie object at 0x000002DAE7122FD0>]
|| |id(obj) |||
|| ||
||one Movie object defined in __main__ ||
| |
|this is a list |
您的 Movie
类需要一个 __repr__
method to represent itself 作为字符串
>>> class X(): pass
...
>>> [X()]
[<__main__.X object at 0x107b9f130>]
>>> class Y():
... def __repr__(self):
... return "string about Y object custom whatever"
...
>>> [Y()]
[string about Y object custom whatever]
作为@Barmar notes in a comment,您还每次循环迭代都重新创建列表,这就是为什么您只能在列表中找到一个条目(而不是随着每个用户输入周期而增长的集合,这可能是您故意的)。您可以将列表分配 ( = []
) 移出循环体以解决此问题!
while True:
lst = [] # creates a new list each loop
# lst refers to the new,empty list
lst = [] # new list created prior to loop
while True:
# lst refers to the list outside the loop
,
您的列表包含一个对象,您可以使用 movieobj.attribute 获取它的特定属性,但附加该对象将为您提供它的内存位置
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。