[英]Trying to use a variable that is inside a function for different functions?
I am having trouble with a certain part of my code. 我在代码的某些部分遇到麻烦。 So basically I'm writing a program about stocks and downloading the prices/dates from the internet, and am having trouble using the list date, which has everything from the webpage in one list, and want to use the variable date in other functions but when I try, it says date does not exist.
因此,基本上,我正在编写一个有关股票的程序,并从互联网上下载价格/日期,并且在使用列表日期时遇到了麻烦,该列表日期将网页中的所有内容都包含在一个列表中,并且想要在其他功能中使用可变日期,但是当我尝试时,它说日期不存在。 Basically I can't call date outside of the function.
基本上我不能在函数之外调用日期。 Can anyone help me please?
谁能帮我吗?
PS The goal that I'm trying to reach is to use the variable date in other functions such as ones that pluck out each date in the list date and put them into one list, and pluck each closing price from the list date and put them into one list. PS:我要达到的目标是在其他功能中使用可变日期,例如,将清单日期中的每个日期均剔除并将其放入一个列表,然后从清单日期中剔除每个收盘价并将其放入中进入一个列表。
def _print_url_contents(response: http.client.HTTPResponse) -> None:
content_bytes = response.read()
content_string = content_bytes.decode(encoding='utf-8')
content_lines = content_string.splitlines()
print()
date = []
for line in content_lines:
date.append(line)
return date
Are you assigning the return value to some variable? 您是否正在将返回值分配给某个变量? If yes, that's how you should access date.
如果是,这就是您应该访问日期的方式。 BTW, why are you annotating that you're returning None, when really you're returning a list of date strings?
顺便说一句,当您实际上返回的是日期字符串列表时,为什么要注释为未返回?
I thought Python 3 type annotations were advisory only, nonbinding. 我认为Python 3类型注释仅是建议性的,没有约束力。 But it still concerns me a little to see a type annotation that's clearly out of sync with reality.
但是看到类型注释显然与现实不同步仍然让我有些担心。
You can return more than one variable and you can send in more than one variable. 您可以返回多个变量,也可以发送多个变量。 So just return all the variables you want to access from the print function to the driver function.
因此,只需将要访问的所有变量从打印功能返回到驱动程序功能即可。
Of course you can't access date
- it would be terrible if you could! 当然,您无法访问
date
-如果可以的话,那会很糟糕! (see the concepts of scope for further explanations). (有关更多说明,请参见范围的概念)。
A possible work around would be to define date
gloabally (poutside your function) and use global date
inside your function if needed. 可能的解决方法是按需定义
date
(在函数的外部),并在需要时在函数内使用global date
。
The other option would be returning date
and passing it to the next function 另一个选择是返回
date
并将其传递给下一个函数
Third option would be to define a dedicated object which exists only once (see "singleton") which keeps the date. 第三种选择是定义一个仅保留一次的专用对象(请参阅“单例”)以保留日期。 But still you'll have to know how to access it (for possible solutions see above)...
但是您仍然必须知道如何访问它(有关可能的解决方案,请参见上文)...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.