我试图在python中访问一个function
中的全局变量,但它的值在函数中没有改变,因为它显然没有引用全局变量,但它认为它是一个新变量。你知道吗
如下所示,我想更改is_new_namespace
=True inside the function
test的值`
这就是我所做的,它不识别变量,但认为它是函数本身中新创建的变量。你知道吗
我需要再次说明的是,我可以访问同一目录下另一个文件中的变量is_new_namespace
吗?如果是,怎么做?你知道吗
from BitesizeDecorator import BitesizeDecorator
import execute
import constants
import subprocess
from custom_check_kubectl import does_kubectl_work
class CreateNamesapce(BitesizeDecorator):
def __init__(self, createnamesapce):
super(CreateNamesapce, self).__init__(createnamesapce)
is_new_namespace = False #global variable
def test(self):
super(CreateNamesapce, self).test()
if does_kubectl_work(self) != 0: # works
does_namespace_available = execute.check_if_exists("kubectl get ns | grep -E \'(^|\s)"+constants.NAMESPACE+"($|\s)\'")
if does_namespace_available != "" and len(does_namespace_available) != 0 : #if exists
print(constants.ORANGE+"\n[6] "+ u'\u0021' +constants.NC+" - "+constants.ORANGE+"Namespace \"" + constants.NAMESPACE +"\" already exists...\n" + constants.NC)
print(does_namespace_available)
else:
is_new_namespace = True #function considers this as a newly created variable
namespace_output = execute.subprocess_execute_arr(["kubectl", "create", "namespace", constants.NAMESPACE])
if namespace_output == 0: # returns zero if executed successfully
print(constants.GREEN+"\n[6] " + u'\u2714' +constants.NC+" - "+constants.GREEN+" Namespace " + constants.NAMESPACE + " created successfully..." + constants.NC + "\n")
else:
print(constants.RED+"\n[6] " + u'\u274C' +constants.NC+" - "+constants.RED+"error creating namespace \"" + constants.NAMESPACE + "\""+constants.NC+"\n")
else:
print(constants.RED + constants.ICON_CROSS + " \"Kubectl\" commmands are not working\n" + constants.NC)
请看下面我对你的代码的评论
在类定义上方添加
is_new_namespace = False
意味着您可以在同一个文件中的任何地方使用它,而无需self
。 要在其他文件中引用此变量,您需要从最初创建它的位置导入它。例如,如果当前代码位于名为file_a.py
的文件中,而您位于名为file_b.py
的新文件中,则需要现在有了在
file_a
中创建的变量另外,在类中首先声明类变量是一种很好的做法,在
def __init__(self)
之上相关问题 更多 >
编程相关推荐