从Python的课堂打印,列表理解
为什么我的打印
在使用循环时从我的班级工作中函数,但是当我使用列表理解打印时返回内存位置?
stocks= ['STY','STY','PRC','STY','PRC','STY','PRC','STY','PRC','STY']
price=[48,46,35,46,235,46,34,64,26,53]
quantity=[10,24,60,24,54,64,10,10,35,10]
type=['sell','sell','sell','sell','sell','buy','buy','buy','buy','buy']
data=list(zip(stocks,price,quantity,type))
print(list(data))
class Order():
def __init__(self, stock_name, cost, quantity, trx_type):
self.stock_name = stock_name
self.cost = cost
self.cost = cost
self.quantity = quantity
self.trx_type = trx_type
def __str__(self):
return '{stock}: {trx} {quant} at ${cost}'.format(stock = self.stock_name, trx = self.trx_type.title(), quant = self.quantity, cost = self.cost)
order_list=[]
for order in data:
stock = Order(stock_name = order[0], cost = order[1], quantity = order[2], trx_type = order[3])
order_list.append(stock)
print([order for order in order_list]) ## This returns list of memory locations
for order in order_list: ## this returns print statements from __str)__
print(order)
Why does my print
function from my Class work when I am using a loop, but return memory locations when I print using a list comprehension?
stocks= ['STY','STY','PRC','STY','PRC','STY','PRC','STY','PRC','STY']
price=[48,46,35,46,235,46,34,64,26,53]
quantity=[10,24,60,24,54,64,10,10,35,10]
type=['sell','sell','sell','sell','sell','buy','buy','buy','buy','buy']
data=list(zip(stocks,price,quantity,type))
print(list(data))
class Order():
def __init__(self, stock_name, cost, quantity, trx_type):
self.stock_name = stock_name
self.cost = cost
self.cost = cost
self.quantity = quantity
self.trx_type = trx_type
def __str__(self):
return '{stock}: {trx} {quant} at ${cost}'.format(stock = self.stock_name, trx = self.trx_type.title(), quant = self.quantity, cost = self.cost)
order_list=[]
for order in data:
stock = Order(stock_name = order[0], cost = order[1], quantity = order[2], trx_type = order[3])
order_list.append(stock)
print([order for order in order_list]) ## This returns list of memory locations
for order in order_list: ## this returns print statements from __str)__
print(order)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在这里,您可以使用列表理解将实例存储在
list
中。当您使用以下方式打印它们时:它将打印实例的
list
(不是一个实例或一个实例,而是一个完整的列表)。由于您将实例存储在列表中,因此它将存储其位置。同样,当您使用循环时:
现在,您正在一个一个实例访问单个实例并打印它们,它将使用类的
__ str __()
函数。Here you're storing instances in a
list
using list comprehension. And when you print them using:it prints the
list
of instances (not a single instance or instances one by one but a complete list). Since you have stored instances in the list, it will store their location.Similarly when you use loop:
Now you're accessing single instances one by one and printing them and it will use the
__str__()
function of the class.