Python 使用动态类的返回值
我有一种我使用的文件类型,其中每一行代表一个不同的模型,每个模型都有特定的属性。从一个文件到另一个文件,这些属性可以更改,所以我编写了动态类来读取这些文件。那是-Python 使用动态类的返回值,python,class,oop,python-2.7,dynamic,Python,Class,Oop,Python 2.7,Dynamic,我有一种我使用的文件类型,其中每一行代表一个不同的模型,每个模型都有特定的属性。从一个文件到另一个文件,这些属性可以更改,所以我编写了动态类来读取这些文件。那是- class readmags: def __init__(self, fname): self.data = open(fname, 'r') # Read header to find the columns in the file while True:
class readmags:
def __init__(self, fname):
self.data = open(fname, 'r')
# Read header to find the columns in the file
while True:
line = self.data.readline()
line = line.lstrip()
if line[0] == '#':
header = line.replace('#', '')
header = header.split()
break
self.header = header
def next(self):
line = self.data.readline()
if line == "":
self.data.close()
raise StopIteration()
# Read in and assign the attributes of the models
cols = line.split()
for i, name in enumerate(self.header):
self.__dict__[name] = float(cols[i])
return self.__dict__
def __iter__(self):
return self
这似乎正是我想要的,然而,它返回的对象的行为让我困惑。我喜欢根据属性选择模型,所以如果我尝试
catalog = readmags(<test_file>)
young = []
for model in catalog:
if model['phase'] != 6.0:
young.append(model)
只返回相同的值。我还不熟悉面向对象编程和制作类,所以我可能只是误解了从readmags返回给我的内容。如果有人能向我解释发生了什么事以及如何做我想做的事,我将不胜感激
编辑以添加要测试的小数据集-
# age log(Z) mass logl logt logg phase log(weight)
5.5000 -2.4089 0.0800 -3.6100 3.3644 5.3500 0.0000 -0.5591
5.5000 -2.4089 0.0900 -3.2700 3.4219 5.2920 0.0000 -0.3456
5.5000 -2.4089 0.1000 -3.0700 3.4492 5.2510 0.0000 -0.4535
5.5000 -2.4089 0.1100 -2.9300 3.4655 5.2180 0.0000 -0.3965
5.5000 -2.4089 0.1300 -2.7300 3.4852 5.1690 0.0000 -0.4183
5.5000 -2.4089 0.1500 -2.4002 3.5584 5.1938 0.0000 -0.3674
还有一个测试程序-
models = readmags(<test_file>)
young = []
for model in models:
if model['age'] == 5.5:
print model['mass']
young.append(model)
for star in young:
print star['mass']
两个打印语句不应该打印出相同的内容吗?它们不是,我也不明白为什么。当您遍历目录时,每次您:
return self.__dict__
这将添加到您的年轻人列表中:
这意味着young包含对同一字典的多个引用,每次调用catalog.next时循环的每次迭代都会修改该字典。因此,当您随后在young上迭代时,您会一次又一次地看到相同的值
您可以返回字典的副本:
return self.__dict__.copy()
或者创建并返回一个新的字典,而不是修改实例的dict。您能提供一个用于测试的最小数据示例吗?为什么要修改实例的_dict _,而不是返回新的结构?我修改了_dict _,以便动态创建类属性。非常感谢。这就解决了问题,我现在明白了问题所在。
young.append(model)
return self.__dict__.copy()