簡體   English   中英

function 內部的變量如何在 python 的 function 之外使用該變量

[英]variable inside of function how to use that variable outside of function in python

如何在 function 內部定義的 function 之外使用變量? Function 應在 class 中聲明。

class A:
  def aFunction(self):
    aVariable = "Hello"

現在在這里我想使用那個aVariable

如果你想在 class A 中使用這個變量,使用實例變量怎么樣?

class A: 
    def aFunction(self): 
        self.aVariable = "Hello"

現在您可以在同一 class 的另一個 function 中使用 self.aVariable

要在 function 或整個 class 之外使用 class 中的變量:

class A:

    def aFunction(self):
        self.aVariable = 1

    def anotherFunction(self):
        self.aVariable += 1

a = A()  # create instance of the class
a.aFunction()  # run the method aFunction to create the variable
print(a.aVariable)  # print the variable
a.anotherFunction()  # change the variable with anotherFunction
print(a.aVariable)  # print the new value 

肯定有更多的選擇,也許其他人會提供,但這些是我想出的選擇。

使用return

class A: 
    def aFunction(self): 
        aVariable = "Hello"
        return aVariable
obj = A()
var = obj.aFunction()
print(var)

使用global

class A: 
    def aFunction(self): 
        global aVariable
        aVariable = "Hello"
obj = A()
obj.aFunction()
print(aVariable)

你可以利用self的優勢

class A: 
    def __init__(self):
        self.aVariable = None
    def aFunction(self): 
        self.aVariable = "Hello"
obj = A()
obj.aFunction()
print(obj.aVariable)

您可以嘗試幾種方法。

class A:
    def aFunction(self):
        self.aVariable = "Hello"
    # you can access self.aVariable in the class
class A:
    def aFunction(self):
        aVariable = "Hello"
        return aVariable
    # use self.aFunction() whenever you need this variable

return關鍵字將返回提供的值。 在這里,您提供了self.aVariable 然后,您可以將該值分配給 class 之外的變量並打印該變量。

class A:

    def aFunction(self):
        self.aVariable = "Hello"
        return self.aVariable

a = A() #==== Instantiate the class
f=a.aFunction() #==== Call the function. 
print(f)

這將打印: Hello

暫無
暫無

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

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