如何从不同的`def()`函数到另一个变量 - python

时间:2014-04-07 06:12:21

标签: python numpy

我有两个不同的功能,如:

def messageWindow():
    # all the necessary operations
    feature_matrix_db = zip( B_mean , G_mean , R_mean, cont_list , ene_list , homo_list , cor_list, dis_list)
    return feature_matrix_db

def open():
    #all the necessary operations
    feature_matrix_ip = zip( B_mean1 , G_mean1 , R_mean1, cont_list1 , ene_list1 , homo_list1 , cor_list1 , dis_list1)
    return feature_matrix_ip

def result():
    COLUMNS = 12
    image_count = 0
    resultlist_key = []
    result_list = list()
    i = 0
    a_list = list()
    b_list = list()
    a_list.append(feature_matrix_ip)
    while i < 70:
        b_list.append(feature_matrix_db[i])
        dist = distance.euclidean(a_list,b_list[i])
        result_list.append(dist)
        resultlist_key = OrderedDict(sorted(enumerate(result_list),key=lambda x:x[0])).keys()
        i = i + 1 

    res_lst_srt = {'values': result_list,'keys':resultlist_key}
    res_lst_srt['values'], res_lst_srt['keys'] = zip(*sorted(zip(res_lst_srt['values'], res_lst_srt['keys'])))
    key = res_lst_srt['keys']

    for i1,val in enumerate(key):
        if i1 < 4:
            image_count += 1
            r, c = divmod(image_count, COLUMNS)
            im = Image.open(resizelist[val])
            tkimage = ImageTk.PhotoImage(resized)
            myvar = Label(win, image=tkimage)
            myvar.image = tkimage
            myvar.grid(row=r, column=c)

前两个def()函数将返回feature_matrix_dbfeature_matrix_ip,我希望将这些结果导入下一个def()函数结果 。它给出了一个错误:

im = Image.open(resizelist[val])
File "E:\Canopy\System\lib\site-packages\PIL\Image.py", line 1956, in open
prefix = fp.read(16)
AttributeError: 'numpy.ndarray' object has no attribute 'read'

欢迎任何建议。提前谢谢!

1 个答案:

答案 0 :(得分:1)

您可能想要了解python中的命名空间和作用域。这里有一些信息:https://docs.python.org/2/tutorial/classes.html

例如您的messageWindow()功能:

def messageWindow():
    # all the necessary operations
    feature_matrix_db = zip( B_mean , G_mean , R_mean, cont_list , ene_list , homo_list , cor_list, dis_list)
    return feature_matrix_db

B_meanG_meanR_meancont_listene_listhomo_listcor_list和{{ 1}}定义?您可以将它们作为参数传递给dis_list

messageWindow()

或在函数中为它们分配一些值,或使用def messageWindow(B_mean , G_mean , R_mean, cont_list , ene_list , homo_list , cor_list, dis_list): # all the necessary operations feature_matrix_db = zip( B_mean , G_mean , R_mean, cont_list , ene_list , homo_list , cor_list, dis_list) return feature_matrix_db 关键字在函数外部为它们分配一些值。但你不能在没有说出他们采取什么价值的情况下打电话给他们。

让我们看一下global的前几行:

result()

同样,def result(): COLUMNS = 12 image_count = 0 resultlist_key = [] result_list = list() i = 0 a_list = list() b_list = list() a_list.append(feature_matrix_ip) 定义在哪里?你可以做的是:

feature_matrix_ip