简体   繁体   English

模块内的可变范围

[英]variable scope within a module

I am being stupid and have read numerous posts or articles but I don't understand the scope of variables in Python. 我很愚蠢,已经阅读了许多文章或文章,但是我不了解Python中变量的范围。

So I have a function in a module & I want to have a constant variable that is available to any function that is the module. 所以我在模块中有一个函数,我想有一个常数变量,该常数可用于该模块的任何函数。

**MyModule.py**

_MYCONST = 65.2

def MyFunc():
    return _MYCONST

However when I run MyFunc in the console all I get is, 但是,当我在控制台中运行MyFunc时,我得到的只是,

Out[12]: <function MyModule.MyFunc>

Why am I getting this output and not 65.2? 为什么我得到此输出而不是65.2?

how did you "run" the function? 您是如何“运行”该功能的? It seems to me like you only wrote Myfunc and forgot the parenthesis. 在我看来,您好像只写了Myfunc却忘记了括号。 Remember that functions need to be called in a certain way to actually run them. 请记住,必须以某种方式调用函数才能实际运行它们。

Try "MyFunc()" 尝试“ MyFunc()”

The return value of the function is returned in the calling function. 该函数的返回值在调用函数中返回。 The function call needs to take () and the necessary parameters. 该函数调用需要采用()和必要的参数。 When you only use the function name, it is a function object. 当您仅使用函数名称时,它是一个函数对象。 According to this, there can be a little trick. 据此,可以有一些技巧。

def my_function()
    return 'value'
f=my_function
print(f())
#result: value

You can give the function an alias, that is a reference.Use this function with an alias. 您可以给该函数一个别名,即引用。将此函数与别名一起使用。 This is the underlying principle of using closures. 这是使用闭包的基本原理。 hope my answer can help you! 希望我的回答能对您有所帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM