简体   繁体   English

为什么从 class 调用多个函数只会返回最近调用的 function?

[英]Why does calling multiple functions from a class only give the return for the most recent function that was called?

I'm trying to create a class to make viewing my data very quick and simple within Jupyter Notebook.我正在尝试创建一个 class 以便在 Jupyter Notebook 中快速简单地查看我的数据。

import color
import h5py

class h5view:
    tempf = h5py.File('juliadata\jul20160102_150km.001.hdf5', 'r')

    def data():
        print(color.YELLOW + 'Data' + color.END)
        templist = []
        for name in h5view.tempf['/Data']:
            templist.append(name)
        return templist
    def metadata():
        print(color.YELLOW + 'Metadata' + color.END)
        templist = []
        for name in h5view.tempf['/Metadata']:
            templist.append(name)
        return templist

This runs without any errors.这运行没有任何错误。 In the next Jupyter Notebook Cell I type在下一个 Jupyter Notebook Cell 中,我输入

h5view.data()
h5view.metadata()

outputs输出

Data
Metadata
['Data Parameters',
 'Experiment Notes',
 'Experiment Parameters',
 'Independent Spatial Parameters',
 '_record_layout']

But before Metadata there should be another returned list.但在元数据之前应该有另一个返回列表。 I tried it with other functions in the class (not listed above), and it always gives the return for the most recently called function, but not for any of the others.我在 class(上面未列出)中尝试了它的其他功能,它总是返回最近调用的 function,但不返回任何其他函数。

If I were to just run h5view.data() Then the output would be如果我只运行h5view.data()那么 output 将是

Data
['Array Layout', 'Table Layout']

How do I stop the list here from disappearing the moment I call another function?当我调用另一个 function 时,如何阻止此处的列表消失?

I tried assigning the function calls to variables, like so:我尝试将 function 调用分配给变量,如下所示:

a = h5view.data()
b = h5view.metadata()
print(a, b)

which gives a new output:这给出了一个新的 output:

Data
Metadata
['Array Layout', 'Table Layout'] ['Data Parameters', 'Experiment Notes', 'Experiment Parameters', 'Independent Spatial Parameters', '_record_layout']

Now the list I want is here, but it is after Metadata.现在我想要的列表在这里,但它在元数据之后。 What I want is something that looks like this:我想要的是看起来像这样的东西:

Data
['Array Layout',
 'Table Layout']
Metadata
['Data Parameters',
 'Experiment Notes',
 'Experiment Parameters',
 'Independent Spatial Parameters',
 '_record_layout']

Is there an easy way to do this, or perhaps another approach I should be taking?有没有一种简单的方法可以做到这一点,或者我应该采取另一种方法?

Python notebooks only print a value if there is no code after it in the cell, which is why h5view.data() is not printing. Python 笔记本只在单元格中没有代码的情况下打印一个值,这就是h5view.data()不打印的原因。 To get the desired result just use print on each of them separately:要获得所需的结果,只需分别对它们中的每一个使用 print :

print(h5view.data())
print(h5view.metadata())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM