所以我有这个代码,并称我为白痴哈哈,但是我不能打印这个,然后是7。
代码:
def function(parameter):
parameter = parameter + 1
parameter = 6
print(function(parameter))
print(parameter == 7)
我需要知道如何更改与函数中的参数同名的变量。
非常感谢任何帮助,如果你不理解这个问题,我很乐意解释更多。
答案 0 :(得分:2)
它打印None
因为您的function()
没有返回任何内容。
它会打印False
,因为parameter
(当前为6
)不等于7
。
要更改被局部变量屏蔽的全局变量,请使用globals()
函数:
def function(parameter):
globals()['parameter'] += 1
答案 1 :(得分:1)
因为我真的讨厌全局变量,所以我会这样做:
def function(parameter):
return parameter + 1
parameter = function(6)
print(parameter)
print(parameter == 7)
<强>输出强>
7
True
基本上,通过指定与参数同名的变量并分配函数,您可以更改parameter
,就好像它是同一个变量一样。请注意,情况并非如此,它实际上并不是同一个对象。但如果您的目标是使用相同的名称,那就可以了。
答案 2 :(得分:0)
将.docx
定义为全局,并且实际上不将其作为参数传递:
<?php
// Build request
$endpoint = "https://api.zamzar.com/v1/jobs";
$apiKey = "YOUR_KEY";
$sourceFilePath = "/tmp/my.doc"; // Or DOCX/PPT/PPTX/XLS/XLSX
$targetFormat = "jpg";
$sourceFile = curl_file_create($sourceFilePath);
$postData = array(
"source_file" => $sourceFile,
"target_format" => $targetFormat
);
// Send request
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $endpoint);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERPWD, $apiKey . ":");
$body = curl_exec($ch);
curl_close($ch);
// Process response (with link to converted files)
$response = json_decode($body, true);
print_r($response);
?>
答案 3 :(得分:0)
可以做的是将其称为global
。更好的方法是使用函数的概念来实现它们:提供任何给定的输入,它们会产生一些结果。
所以,您可能想要使用return
:
def fun(val):
return val;
parameter = val(10)
print(parameter) # prints '10'
但是,如果你想引用变量,在python中你可以做各种疯狂的事情,比如将模块范围作为对象访问并在那里改变它的值:
def fun(val):
import sys;
sys.modules[__name__].parameter = val
parameter = 10
fun(1)
print(parameter) # prints '1'
然而,我之所以称之为疯狂,是因为如果一个功能有副作用,你就永远无法从外面说出来。这就是你想要避免的复杂性。因为您的代码应尽可能可预测。显而易见的原因。
答案 4 :(得分:0)
使用全局变量既不是线程安全也不推荐。看起来最干净的解决方案是将参数参数传递给可变容器。见https://docs.python.org/3/faq/programming.html#how-do-i-write-a-function-with-output-parameters-call-by-reference