如何在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)

如果你只想在类外定义变量,除非你打算修改它,否则不需要使用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("")

我找到了解决方案。Barmar感谢您。它奏效了。

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":

如果您引用的是静态,则Class.valinstance.val中可用的内容引用相同的内容;你可以在类主体中声明一个

class A:
val = None # Static variable
def __init__(self, x, y):
# Instance variables
self.x = x
self.y = y
inst_1 = A(2, 3)
inst_2 = A("a", "b")
print(A.val)
# static can't be modified via instance, only A
A.val = "abcd"
print(inst_2.val) # static modified across As
# Unique to each instance
print(inst_1.x)
print(inst_2.x)

相关内容

  • 没有找到相关文章

最新更新