【问题标题】:Can't get variables from a function inside a class (python)无法从类内的函数中获取变量(python)
【发布时间】:2021-06-05 15:01:17
【问题描述】:

我遇到了这个问题,我无法从函数 run_sensor 中读取变量 bpmspo2(我需要这些另一个脚本中的两个变量)。如果有人可以帮助我,谢谢。

class HeartRateMonitor(object):
LOOP_TIME = 0.10

def __init__(self, print_raw=False, print_result=False):
    self.bpm = 0
    if print_raw is True:
        print('IR, Red')
    self.print_raw = print_raw
    self.print_result = print_result



def run_sensor(self):
    sensor = MAX30102()
    ir_data = []
    red_data = []
    bpms = []
    
    # run until told to stop
    while not self._thread.stopped:
        # check if any data is available
        num_bytes = sensor.get_data_present()
        if num_bytes > 0:
            # grab all the data and stash it into arrays
            if len(ir_data) == 100:
                bpm, valid_bpm, spo2, valid_spo2 = hrcalc.calc_hr_and_spo2(ir_data, red_data)       # <-------------- here
                if valid_bpm:
                    bpms.append(bpm)
                    while len(bpms) > 4:
                        bpms.pop(0)
                    self.bpm = np.mean(bpms)
                    if (np.mean(ir_data) < 50000 and np.mean(red_data) < 50000):
                        self.bpm = 0
                        if self.print_result:
                            print("Finger not detected")
                    if self.print_result:
                      
                        print("BPM: {0}, SpO2: {1}".format(round(self.bpm), round(spo2)))  
                
                        

【问题讨论】:

  • 你的缩进错误
  • 另一个脚本是什么?如果它在另一个文件中,您应该重新考虑您的设计。也许bpmspo2 应该是类的属性?您正在尝试在另一个脚本中使用函数的局部变量,这是无法完成的。答案给出了使用global 的(糟糕的)建议,这可能有效,但通常不是一个好主意。
  • 另一个脚本将这两个变量用于 Web 仪表板,当我尝试使用全局时,它会给我错误或值保持为 0。
  • 我尝试将 bpm 和 spo2 分配给其他变量,但它一直为 0

标签: python multithreading function class


【解决方案1】:

您需要为此问题使用全局关键字。写这个 -

global bpm

global spo2

函数下你需要用到的变量

【讨论】:

  • 好吧,首先python是区分大小写的,所以Global应该是global。更重要的是——这是一个非常糟糕的建议,尤其是在 OOP 环境中。
【解决方案2】:

您不能从另一个函数访问类变量。但是,如果您要创建HeartRateMonitor 类的实例,则可以导入它并获取它的bpmspo2

instance = HeartRateMonitor()

然后,在您的其他脚本中:

from heartratemonitor.py import instance
instance.run_sensor() # I assume this is what you want to do
print(instance.bpm)
print(instance.spo2)

【讨论】:

  • 嗨,我试过了,现在它给了我这个错误:File "fla.py", line 9, in &lt;module&gt; instance.run_sensor() File "/home/pi/Desktop/heartrate_monitor.py", line 32, in run_sensor while not self._thread.stopped: AttributeError: 'HeartRateMonitor' object has no attribute '_thread'
  • 你在哪里定义_thread?你必须先定义它。
  • 抱歉格式化,我无法发布整个代码,在最后一行之后:def start_sensor(self): self._thread = threading.Thread(target=self.run_sensor) self._thread.stopped = False self._thread.start() def stop_sensor(self, timeout=2.0): self._thread.stopped = True self.bpm = 0 self._thread.join(timeout)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-23
  • 1970-01-01
  • 1970-01-01
  • 2022-01-20
  • 2017-05-05
  • 1970-01-01
相关资源
最近更新 更多