Python函数在单独的文件结构中无法调用。

huangapple go评论65阅读模式
英文:

Python functions in separate file structure cannot be called

问题

我尝试重新组织我的Python(Python版本3.9.2)项目,并创建了以下文件结构(我在Macbook Air M2上使用VS Code)。当我尝试在“函数文件结构”中调用函数时,我收到以下错误消息:

> NameError: name 'getAssetHoldings' is not defined

```python
# 文件结构:
# main.py
my_functions
 __init__.py
 stock_functions.py
 utility_functions.py

# 文件内容:
# main.py:
import my_functions
import pandas as pd
import seaborn as sns

# 加载交易文件
filepath_transact = os.path.abspath(f"/Users/Sandbox/Data/transactions.csv")
df_sq = pd.read_csv(filepath_transact, encoding="ISO-8859-1", sep=';')

# 获取资产持仓(该函数位于stock_functions.py中)
df_assets = getAssetHoldings(df_sq)
print('资产:', '\n', df_assets, '\n')

# __init__.py:
from .stock_functions import *
from .utility_functions import *
print('你好')

# stock_functions.py:
import pandas as pd
import yfinance as yf
import pandas_market_calendars as mcal

def getAssetHoldings(df):
    df_numberAssets_k = df_transactions[df_transactions['Transaktionen'].isin(['Buy'])]
    df_numberAssets_k = df_numberAssets_k[['Symbol', 'Quantity']]
    df_numberAssets_v = df_transactions[df_transactions['Transaktionen'].isin(['Sell'])]
    df_numberAssets_v = df_numberAssets_k[['Symbol', 'Quantity']]
    ....
    return df_current_assets

我尝试了多次重新启动内核并多次导入库和函数。


<details>
<summary>英文:</summary>

I have tried to organize my Python (Python version 3.9.2) project better and have created following file structure (I am using VS Code on Macbook Air M2). When I try to call a function in the &quot;function file structure&quot; I get the following error message:

&gt; NameError: name &#39;getAssetHoldings&#39; is not defined

File structure:

main.py

my_functions
init.py
stock_functions.py
utility_functions.py

Content of files:

#main.py:
import my_functions
import pandas as pd
import seaborn as sns

load transaction file

filepath_transact = os.path.abspath(f"/Users/Sandbox/Data/transactions.csv")
df_sq = pd.read_csv(filepath_transact,encoding = "ISO-8859-1",sep=';')

get asset holdings (function resides in stock_functions.py)

df_assets = getAssetHoldings(df_sq)
print('Assets:', '\n',df_assets,'\n')

#_init.py:
from .stock_functions import *
from .utility_functions import *
print('hello')

#stock_functions.py:
import pandas as pd
import yfinance as yf
import pandas_market_calendars as mcal

def getAssetHoldings(df):
df_numberAssets_k = df_transactions[df_transactions['Transaktionen'].isin(['Buy'])]
df_numberAssets_k = df_numberAssets_k[['Symbol','Quantity']]
df_numberAssets_v = df_transactions[df_transactions['Transaktionen'].isin(['Sell'])]
df_numberAssets_v = df_numberAssets_k[['Symbol','Quantity']]
....
return df_current_assets


I tried to restart the kernel and import the libraries and functions several times.


</details>


# 答案1
**得分**: 1

为了关闭这个问题,我在这里写出了评论中提出的解决方案。
为了更清晰,我重新编写了问题的主要结构:


├─ main.py

└─ my_functions/
├─ init.py
├─ stock_functions.py
└─ utility_functions.py


正如@Roberto所述,问题在于`__init__.py`文件需要双下划线。而且在`main.py`文件内部,函数必须通过点符号`my_functions.getAssetHoldings(...)`调用,因为模块是通过`import my_functions`导入的。

<details>
<summary>英文:</summary>

To close this question, I write here the solutions proposed in the comments.
To be more clear I re-write the main structure of the question: 


├─ main.py

└─ my_functions/
├─ init.py
├─ stock_functions.py
└─ utility_functions.py

 
As @Roberto stated, the problem was that the `__init__.py` file needs the double underscore. And inside the `main.py` file, the function has to ba called through the dot notation `my_functions.getAssetHoldings(...)` since the module is imported with the line `import my_functions`.

</details>



huangapple
  • 本文由 发表于 2023年2月18日 22:49:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/75494131.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定