簡體   English   中英

如何在 python 中的 class 中定義全局變量

[英]How to define global variable in class in python

我想在 class 之外取一個變量,但不在文件之外。 我在 class 之外有一個條件,但我也必須在 class 中使用它。 我可以這樣做嗎?

如果它有效,這是嘗試的示例。 我想擦除輸入部分並使用全局變量。

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

這是 class 的外部。

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)

如果您只想在 class 之外定義變量,則不需要使用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)

我不確定您要做什么,但也許您只需要在 class 之外的ask=input("")上方進行global ask

我找到了解決方案。 來自巴爾瑪的感謝。 有效。

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

如果您指的是 static,則可以從Class.valinstance.val獲得相同的東西; 您可以在 class 正文中聲明一個

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM