繁体   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