为什么我的python类实例变量不更新?

问题描述 投票:1回答:1

我有一个类,该类利用将函数作为输入arg的外部定义函数(process_point)。我将类实例函数传递给导入的函数process_point(),该函数应允许process_point调用我的函数。似乎可以做到这一点,但是类实例变量last_pos似乎没有更新。如果我在输出的最后一行打印last_pos,则last_pos似乎会发生变化,但是在下一次回调时,它会返回到原来的位置。除了回调和__init__之外,没有其他代码可以访问last_pos。我有些沮丧,也许看了太多。为了简洁起见,下面是该代码的精简版。对于信息,我有一个可以使用的代码版本,尽管它不使用类结构,并且last_pos是全局变量。如果有道理,我故意选择使用类来摆脱全局变量。

如果您能阐明我的失败,我将永远爱您。

from elsewhere import process_point, Status

class Processor:
    def __init__(   self,
                    in_path, 
                    z_file_path): 

        output_path = "../output"

        self.in_file = in_path
        self.z_file = z_file_path
        self.out_folder = output_path

        self.status = Status()
        self.last_pos = 0
        self.rotations = []
        self.results = []

        # load z
        print('using z file '+self.z_file)
        with open(self.z_file, 'r') as f:
            self.z_vals = json.load(f)

    def the_callback(self, idx, pos, blah, blah2):
        # does some stuff...

        # and then...
        # detect roll over from 360 to 0
        if pos < self.last_pos:
            print("pos:", pos, "last_pos:", self.last_pos)

        self.last_pos = copy.copy(pos)

    def run(self):
        with open(self.in_file, 'rb') as f:
            reader = special.Reader(f)

            for i in reader:
                data = i.fred
                process_point(data, 0, self.status, self.the_callback)

if __name__ == '__main__':

    processor = Processor('../thing.blah', 'nother_thing.blah')
    processor.run()

python instance-variables
1个回答
0
投票

好吧,我找到了这个问题……。似乎其他地方有一个无声的异常正在与代码捆绑。在某些情况下,代码似乎在回调之前轰炸了。我不能说我完全理解为什么,但是我解决了导致静默异常的问题,它开始起作用。也许此信息对其他人有用。

© www.soinside.com 2019 - 2024. All rights reserved.