首页 > 解决方案 > 如何在python的类中定义全局变量

问题描述

我想在类之外取一个变量,而不是在文件之外。我在课外有一个条件,但我也必须在课堂上使用它。我可以这样做吗?

如果它有效,这是尝试的示例。我想擦除输入部分并使用全局变量。

class ComplexMethods:
    ask = input("What type you are writing? (absolute value and phase angle or real and imaginary parts)")
    if ask == "real and imaginary parts":

我试过这个但不工作。它给出了未定义的名称“询问”。

class ComplexMethods:
     global ask
     if ask == "real and imaginary parts":

这是课外。

ask = input("What type you are writing? (absolute value and phase angle or real and imaginary parts)")
if ask == "real and imaginary parts":
    firstcomplexreal = float(input("Enter real part of first complex number: "))
    firstcompleximaginary = float(input("Enter imaginary part of first complex number: "))
    secondcomplexreal = float(input("Enter real part of second complex number: "))
    secondcompleximaginary = float(input("Enter imaginary part of second complex number: "))
    complexnumbers = ComplexMethods(firstcomplexreal, firstcompleximaginary, secondcomplexreal,
                                    secondcompleximaginary)

标签: pythonpython-3.xclassglobal-variables

解决方案


如果您只想在类之外定义变量,则不需要使用global关键字,除非您打算修改它。如果您只想读取变量而不修改它,您可以执行类似的操作。

ask = input("What type you are writing? (absolute value and phase angle or real and imaginary parts)")

class ComplexMethods:
    if ask == "real and imaginary parts":
        pass

if ask == "real and imaginary parts":
    firstcomplexreal = float(input("Enter real part of first complex number: "))
    firstcompleximaginary = float(input("Enter imaginary part of first complex number: "))
    secondcomplexreal = float(input("Enter real part of second complex number: "))
    secondcompleximaginary = float(input("Enter imaginary part of second complex number: "))
    complexnumbers = ComplexMethods(firstcomplexreal, firstcompleximaginary, secondcomplexreal,
                                    secondcompleximaginary)


推荐阅读