Py学习  »  Python

Python将数组从一个函数传递到另一个函数

Clauric • 5 年前 • 1875 次点击  

我希望将变量从一个函数传递到另一个函数,而不需要重新运行SQL连接。

第一个功能是:

def SQL_Country():
    conn = psq.connect("localhost","root","root","world",cursorclass=psq.cursors.DictCursor)
    query = "SELECT * FROM country"

    with conn:
        cursor = conn.cursor()
        cursor.execute(query)
        country = cursor.fetchall()

        global df 
        df = pd.DataFrame(country, columns=["Code", "Name", "Continent", "Population", "HeadOfState"])

第二个函数,我希望传递 SQL_Country() 是:

def assignment():

    ## do something here

    elif Choice == 6:
        try:
            x = df
        except NameError:
            x = None

        if x is None:

            print()

            df = SQL_Country(df)

  File "Python.py", line 185, in assignment
    df = SQL_Country(df)
UnboundLocalError: local variable 'df' referenced before assignment

关于如何将输出从一个函数传递到另一个函数,有什么建议吗?

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/53244
 
1875 次点击  
文章 [ 4 ]  |  最新文章 5 年前
Reedinationer
Reply   •   1 楼
Reedinationer    6 年前

我觉得你应该 review python functions

您定义的函数

def SQL_Country():

但是,当您要使用函数时,您要在以下位置提供参数(该参数不应作为函数输入):

df = SQL_Country(df)

此外,您的功能:

def assignment():

可能还应该输入一个数据帧,使其看起来像:

def assignment(df):

此时,对函数的后续调用将是:

assignment(df)

assignment()
Andy Hayden
Reply   •   2 楼
Andy Hayden    6 年前

您应该在SQLúu County内返回df而不是global:

        global df 
        df = pd.DataFrame(country, columns=["Code", "Name", "Continent", "Population", "HeadOfState"])

应该是:

        return pd.DataFrame(country, columns=["Code", "Name", "Continent", "Population", "HeadOfState"])

然后使用:

df = SQL_Country()

import functools

@functools.lru_cache(maxsize=1)
def SQL_Country():
   ...

这样,数据库获取只完成一次。


In [11]: @functools.lru_cache(maxsize=1)
         def foo():
             print(1)
             return 2

In [12]: foo()
1
Out[12]: 2

In [13]: foo()
Out[13]: 2
pdrersin
Reply   •   3 楼
pdrersin    6 年前

第二个函数缺少参数:

def assignment(df):
MichaelD
Reply   •   4 楼
MichaelD    6 年前

不需要重新运行 SQL_Country() 第二次作为 df

df_country = None

def SQL_Country():
    if df_country is None:
        conn = psq.connect("localhost","root","root","world",cursorclass=psq.cursors.DictCursor)
        query = "SELECT * FROM country"

        with conn:
            cursor = conn.cursor()
            cursor.execute(query)
            country = cursor.fetchall()

            df_country = pd.DataFrame(country, columns=["Code", "Name", "Continent", "Population", "HeadOfState"])
    return df_country

现在当你调用这个函数时,它不会第二次执行它,但是你会得到你想要的值

def assignment():
    ## do something here
    if Choice == 6:
         # No need to do the name check
        x = SQL_Country()
        if x is None:
            print()