对象在列表理解中不包括方法 [英] Objects does not include methods in the list comprehension
问题描述
这个问题与 我之前的问题和比尔在那里的回答.
This question is related to my previous question and Bill's response there.
在subfile.py中有一个名为StrucData的类
I have a class named StrucData in subfile.py
class StrucData:
def __init__(self, name):
self.name=name
def loadData(self, size=1, cost=1):
self.size=size
self.cost=cost
return self
在主文件I:
- 调用子文件,
- 创建数据名称列表
- 在列表中循环以实例化对象;和
- 使用'loadData'方法为每个对象加载数据(为了使本示例易于使用,我使用相同的'size'和'cost').
使用列表理解功能一次完成
in one go using a list comprehension:
# in the main file
from subfile import StrucData
listIndex=['data1','data2','data3']
listObjects = [StrucData(idx).loadData(size=3, cost=4) for idx in listIndex]
输出为
listObjects=[object1, object2, object3]
,其中每个对象都包含其在subfile.py中定义的属性(名称,大小,成本).
in which each object contains its attributes defined in the subfile.py (name, size, cost).
我想知道的是,当我使用相同的代码定义一个对象时
What I wonder is when I define one object using the same code as
x=StrucData(listIndex[0]).loadData(size=3, cost=4)
它也包含方法"loadData".
it contains the method 'loadData' too.
有人可以向我解释为什么会发生吗?
Could anyone please explain to me why it happens?
我使用Spyder的anaconda3发行版,版本信息是
I use anaconda3 distribution of Spyder, the version information is
推荐答案
在Spyder中调试应用程序时使用的检查器将列表中的对象与相同类型的单个对象区别对待.它只是显示不同的内容,并且-如果在列表中-则省略了功能.
The inspector used when debugging your application inside Spyder treats objects inside lists differently from singular objects of the same type. It simply displays different things and - if in a list - omits function.
您可以通过打印轻松地检查两个对象是否都具有此方法:
You can easily check if both objects have this method by printing it:
listIndex = ['data1','data2','data3']
listObjects = [StrucData(idx).loadData(size=3, cost=4) for idx in listIndex]
other = StrucData("other").loadData(size=3, cost=4)
print(listObjects[0].loadData)
print(other.loadData)
您可以将列表元素之一分配给普通变量,然后检查其检查器输出以验证:
You can assign one of the list elements to a normal variable and check its inspector output to verify:
lO = listObjects[1]
设置一个断点并检查它-现在该方法显示出来.
Set a breakpoint and inspect it - now the method shows up.
原因:询问负责Spyder调试检查程序代码的编码人员.作为一个危险的猜测:当显示捆绑在列表中的对象时,要节省屏幕空间.
As to the why: ask the coders responsible for Spyder's debugging inspector code. As a hazarded guess: to save screen estate when displaying objects that are bundled inside a list.
这篇关于对象在列表理解中不包括方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!