【问题标题】:How can I define the type of variable given into a function parameter using Python?如何使用 Python 定义给定函数参数的变量类型?
【发布时间】:2021-11-14 11:55:42
【问题描述】:

我有一个带有变量文件的 Python 函数。我现在的问题是,我想使用文件名。

我现在的问题是,函数内部不自动知道变量的类型。我有哪些简单的可能性可以确定变量是文件?

   import pandas_datareader as web
   import pandas as pd
   import pickle


   def import_prices(file, start, end):
       tickers = pickle.load(file)
       main_df = pd.DataFrame()
       i = 0
       for ticker in tickers:
           df = web.DataReader(ticker, 'yahoo', start, end)
           df.rename(columns={"Adj Close": ticker}, inplace=True)
           df.drop(columns=["Open", "High", "Low",
                "Close", "Volume"], inplace=True)
           if main_df.empty:
               main_df = df
           else:
               main_df = main_df.join(df, how='outer')
           i = i + 1
           print(i)
       main_df.to_csv('Webscrapper/{}_prices.csv'.)

我要插入括号中的点后没有内容的文件名

main_df.to_csv('Webscrapper/{}_prices.csv'.)

【问题讨论】:

    标签: python file variables


    【解决方案1】:

    file 变量应该包含我在您的代码中看到的文件名。您可以检查以下内容以确保文件包含字符串值isinstance(file, str)

    您还可以使用更复杂的检查,例如 isinstance(file, pd.DataFrame)

    from io import IOBase
    
    isinstance(someobj, IOBase)
    

    最好在函数定义中使用类型提示。我假设 startend 是整数,但您可以更改它以匹配正确的类型。

    def import_prices(file: str, start: int, end: int) -> None
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-12
      • 2012-02-14
      • 1970-01-01
      • 1970-01-01
      • 2019-01-02
      相关资源
      最近更新 更多