简体   繁体   English

从python模块正确返回布尔变量

[英]Correctly return boolean variable from python module

I'm sure this is absurdly simple but I have been unable to get it working.我确信这非常简单,但我一直无法让它工作。

I want to convert a boolean variable to True in a module and return it to my main.我想在模块中将布尔变量转换为True并将其返回到我的主程序。

file: test文件:测试

import module as mo

value = False
mo.x(value)
print(value)

2. file: module 2.文件:模块

def x(value):
    value = True
    return value

But this code is not working.但是这段代码不起作用。 When I print out the value it gives me a False .当我打印出该值时,它给了我一个False Does anybody know how to return the value so it's True ?有谁知道如何返回值所以它是True Or is it even possible to change a boolean value in another module and return it afterwards?或者甚至可以在另一个模块中更改布尔值并在之后返回它?

You're not printing the return value of the funtion.您没有打印函数的返回值。 For that, you should为此,你应该

v = mo.x(value)
print(v)

Otherwise, you're printing the local variable value .否则,您将打印局部变量value

You are printing out value instead of the result of mo.x(value) .您正在打印value而不是mo.x(value)的结果。

In your test.py, try the following:在您的 test.py 中,尝试以下操作:

import module as mo

value = False
value = mo.x(value)
print(value)

and the output will be:输出将是:

>>> True

Note that the variables defined inside a function have a local scope.请注意,函数内部定义的变量具有局部作用域。 This means that value variable inside function x is only accessible within the function and is not the same as the value variable in your test.py module.这意味着函数x中的value变量只能在函数内访问,并且与test.py模块中的value变量不同。

The problem is, that primitive types, like integers are passed by value and not by reference.问题是,原始类型(如整数)是按值传递而不是按引用传递的。 So what happens is, you don't pass the variable "value" to function x(), but the value inside "value" gets copied.所以发生的情况是,您没有将变量“value”传递给函数 x(),而是“value”中的值被复制。

A workaround would be using any object, as they are always passed by reference.解决方法是使用任何对象,因为它们总是通过引用传递。 Eg: A list:例如:一个列表:

value[0] = False
mo.x(value)

def x(value: list):
    value[0] = True
    return value

This happens because you are returning "True" value but you dont assign it to "value" variable.发生这种情况是因为您正在返回“真”值,但没有将其分配给“值”变量。 So, you are just making the call to the function but not using the return value.因此,您只是调用该函数,而不是使用返回值。

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

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