【问题标题】:How to retrieve value of objects/ variables from one function to another and calling the two functions by main?如何从一个函数检索对象/变量的值到另一个函数并通过 main 调用这两个函数?
【发布时间】:2020-08-07 14:28:33
【问题描述】:

我试图从 kindle() 中获取值并在 bundle() 中处理它们并在 main 中调用这两个函数,但我收到错误:NameError: name 'x' is not defined at bundle()'s第一行,而 x 是全局声明的。

class Program:

    x = 0
    y = 0
    def kindle(self):
        x = 2
        y = 3
    return x, y

    def bundle(self):
        z = x+ y
        print(z)

def main():
    p = Program()
    p.kindle()
    p.bundle()
if __name__ == "__main__":
    main()

【问题讨论】:

  • 我猜你想要self.x
  • @MateenUlhaq 是的,我如何为相同的语法编写语法,请您帮忙。谢谢

标签: python function variables main


【解决方案1】:

啊,关于课程的讨论。因此,您“全局”定义的 x 和 y 并不是真正的全局,它们是类对象并从类中访问。例如,

class thing:
    x = 10
    def func(self):
        print(thing.x)

请注意,“x”附加到“事物”类。因此,“x”不是全局的。一般来说,类内部的任何东西都可以通过类访问,而不是外部空间的一部分。

当然,使用类的主要好处之一是所有函数和变量共享一个公共命名空间。这个命名空间的一个实例被称为“self”,它会自动传递给所有的类函数。因此,完全没有必要做“thing.x”(并且要求我知道类的名称)。相反,我们可以这样做:

class thing:
    x = 10
    def func(self):
        print(self.x)

我们当然可以走得更远。如果我可以在课堂上随时访问自我,那么如果我附加到自我,其他功能将能够自动看到该附件。让我们试试:

class Program:

    x = 0 #Default value if we don't overwrite. 
    y = 0 #Default value if we don't overwrite. 

    def kindle(self):
        self.x = 2 #Overwrote the default. 
        self.y = 3 #Overwrote the default. 
        #No need to return anything. Self already has x and y attached.

    def bundle(self):
        z = self.x + self.y
        print(z)
        #z is not attached to self, hence z is only available in this function. 

def main():
    p = Program() #Create an instance of the Program class. 
    p.kindle()    #Overwrite the default x and y values for just this instance.
    p.bundle()    #Add the values and print. 

if __name__ == "__main__":
    main()

【讨论】:

    猜你喜欢
    • 2015-05-16
    • 2017-11-04
    • 2016-06-08
    • 1970-01-01
    • 1970-01-01
    • 2015-04-12
    • 2016-07-14
    • 2019-04-07
    • 2014-11-13
    相关资源
    最近更新 更多