简体   繁体   English

从同一类的另一个函数访问变量

[英]Accessing the variable from another function of the same class

from folder_exp import my_tcommands as t
class Gravity(EarthG):
    def __init__(self):
        super(Gravity, self).__init__()

    def check(self):
        original = t.get_gravity()
        print "Original gravity from the function:", original
        my_gravity = 9.888
        t.set_gravity(my_gravity)


    def verify(self):

I have to load original gravity here in verify using t.set_gravity(original) but I have already re-written the gravity using t.set_gravity(my_gravity) in check function hence if I do t.get_gravity again, it gives me 9.888 and not the original one . 我必须在这里使用t.set_gravity(original)加载原始重力以进行verify但是我已经在check功能中使用t.set_gravity(my_gravity)重新编写了重力,因此如果再次执行t.get_gravity ,它会给出9.888 and not the original one

What is the way to access original from check so that I can do the following operation in verify method. check访问original的方法是什么,以便我可以在verify方法中执行以下操作。

def verify(self):
    t.set_gravity(original)

The name original and, potentially, the object to which it refers disappear once the enclosing function returns. 封闭函数返回后, original名称以及可能引用的对象名称将消失。 If you want to access it later, you have to create a new name which will not go out of scope so soon. 如果以后要访问它,则必须创建一个新名称,该名称不会很快消失。

A convenient place to store it is in the object itself: 一个方便的存储位置是在对象本身中:

def check(self):
    self.original = t.get_gravity()
    print "Original gravity from the function:", self.original
    my_gravity = 9.888
    t.set_gravity(my_gravity)

A subsequent invocation will see that object: 后续调用将看到该对象:

def verify(self):
    t.set_gravity(self.original)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM