python中如何在类中定义全局变量

2024-03-29 12:54:19 发布

您现在位置: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":

我试过这个但没用。它给出的名称“ask”没有定义。你知道吗

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)

Tags: andofnumberinputiffloatrealask
3条回答

我找到了解决办法。巴玛谢谢你。成功了。你知道吗

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


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

如果您只想在类之外定义变量,则不需要使用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)

我不太清楚你想做什么,但也许你只需要 global ask 高于你的 ask=input("")在类外。你知道吗

相关问题 更多 >