简体   繁体   English

如何从另一个类运行函数并使用其变量?

[英]How To Run A Function From Another Class & Use Its Variable?

I'm a beginner in Python working on a simple app for our final year project. 我是Python的初学者,为我们的最后一年项目开发一个简单的应用程序。 This is the only part that I can't solve and I would really appreciate your help. 这是我无法解决的唯一部分,我非常感谢你的帮助。 I need to take a value from a live updating csv file, fetch the first element and match it with the reference csv. 我需要从实时更新csv文件中获取值,获取第一个元素并将其与引用csv匹配。 That part is already working. 那部分已经有效了。 Then I need it to play the corresponding sound as per the playsound. 然后我需要它根据playound播放相应的声音。 That part is also already working. 那部分也已经有效了。

However, since it will be situated in a Kivy app, I need to create multiple classes. 但是,由于它将位于Kivy应用程序中,因此我需要创建多个类。 Some will handle the data processing side and the Kivy part will handle the display part. 有些将处理数据处理方,Kivy部分将处理显示部分。 But my question today focuses on the Python part not in Kivy. 但我今天的问题集中在不在Kivy的Python部分。

The first class handles the csv, playsound, and numpy matching. 第一个类处理csv,playound和numpy匹配。

The second class is where I tried to call the functions of the first class to get them running. 第二个类是我试图调用第一个类的函数来让它们运行的​​地方。 I also tried to get the where variable present in the first class so that I could use it in an if statement to verify a match and output a text display. 我还尝试在第一个类中获取where变量,以便我可以在if语句中使用它来验证匹配并输出文本显示。

import serial
import sys
import numpy as np
import time
import csv
import os
import string 
import collections
from playsound import playsound
from pathlib import Path
import os, sys



#import keyboard
class Identifier:
    def csvwriter(self): #function for writing csv file
        try:
            ser = serial.Serial('COM10', baudrate=9600)
            ser.flushInput()

            while True:
                ser_bytes = ser.readline()
                print(ser_bytes)
                file = open("letterz5.csv", "a")
                file.write(str(ser_bytes))
                file.close()

         #       if keyboard.is_pressed('esc'):
         #           break;

            ser.close
        except:
            print("Unexpected error:", sys.exc_info()[0])
            print("Unexpected error:", sys.exc_info()[1])
    def fn_voice(self): #function for parsing and comparing csv file.
        count=1
        while (count>0):
            livecsv=np.genfromtxt("lettera.csv", delimiter=",", skip_header=1, filling_values=np.nan, dtype=int, case_sensitive=True, deletechars='', replace_space=' ')
            refcsv=np.genfromtxt("refcsv1.csv", delimiter=",", skip_header=1, filling_values=np.nan, dtype=int, case_sensitive=True, deletechars='', replace_space=' ')
            A=np.array(livecsv)
            B=np.array(refcsv)
            D = B - A[-1]
            match= B[np.abs(D).sum(axis=1).argmin()]
            where=match[0]
            voice=fn_voice(where)
            time.sleep(1)
            count = count + 1
        var=where
        if var==1:
            A=playsound('audio-alphabet/A.wav',True)
            return A
        elif var==2:
            B=playsound('audio-alphabet/B.wav',True)
            return B
        elif var==3:
            C=playsound('audio-alphabet/C.wav',True)
            return C
        elif var==4:
            D=playsound('audio-alphabet/D.wav',True)
            return D
        elif var==5:
            E=playsound('audio-alphabet/E.wav',True)
            return E
        elif var==6:
            F=playsound('audio-alphabet/F.wav',True)
            return F
        elif var==7:
            G=playsound('audio-alphabet/G.wav',True)
            return G
        elif var==8:
            H=playsound('audio-alphabet/H.wav',True)
            return H
        elif var==9:
            I=playsound('audio-alphabet/I.wav',True)
            return I
        elif var==10:
            J=playsound('audio-alphabet/J.wav',True)
            return J
        elif var==11:
            K=playsound('audio-alphabet/K.wav',True)
            return K
        elif var==12:
            L=playsound('audio-alphabet/L.wav',True)
            return L
        elif var==13:
            M=playsound('audio-alphabet/M.wav',True)
            return M
        elif var==14:
            N=playsound('audio-alphabet/N.wav',True)
            return N
        elif var==15:
            O=playsound('audio-alphabet/O.wav',True)
            return O
        elif var==16:
            P=playsound('audio-alphabet/P.wav',True)
            return P
        elif var==17:
            Q=playsound('audio-alphabet/Q.wav',True)
            return Q
        elif var==18:
            R=playsound('audio-alphabet/R.wav',True)
            return R
        elif var==19:
            S=playsound('audio-alphabet/S.wav',True)
            return S
        elif var==20:
            T=playsound('audio-alphabet/T.wav',True)
            return T
        elif var==21:
            U=playsound('audio-alphabet/U.wav',True)
            return U
        elif var==22:
            V=playsound('audio-alphabet/V.wav',True)
            return V
        elif var==23:
            W=playsound('audio-alphabet/W.wav',True)
            return W
        elif var==24:
            X=playsound('audio-alphabet/X.wav',True)
            return X
        elif var==25:
            Y=playsound('audio-alphabet/Y.wav',True)
            return Y
        elif var==26:
            Z=playsound('audio-alphabet/Z.wav',True)
            return Z
        os.system("rm lettera.csv")



class LetterAScreen(Identifier):
    def identity(self): #I tried to call the functions of Identifier class here but they won't run
        fn_voice() #I need the playsound part to only return playsound when the input data is correct
        fn_csvwriter()
        iden=fn_voice().where #I need to get the variable 'where' from fn_voice() but I can't seem to get it
     def verifier(self):
        verify=identity.iden
        if verify == 1:
            print ("correct")
        else:
            print ("incorrect")

How do I go about this? 我该怎么做? How do I get all of the first class running, and how do I fetch the where variable so that I can use it in the verifier function? 如何让所有第一个类运行,以及如何获取where变量以便我可以在verifier函数中使用它? Thank you very much. 非常感谢你。

In python you cannot access variables like you have done with fn_voice().where . 在python中,你不能像使用fn_voice().where那样访问变量。

Read up some more on scope at https://pythonspot.com/scope/ . 请阅读https://pythonspot.com/scope/上有关范围的更多信息。

The solution to your problem will be to assign the where reference (variable) in the class rather than the method. 问题的解决方案是在类中分配where引用(变量)而不是方法。

class Identifier:
    where = None
    def fn_voice(self):
        where = match[0]

Then you will be able to access where like: 然后,你将能够访问where ,如:

Identifier.where

NB. NB。 Remember to check if the value of where is None . 请记住检查where的值是否为None We can use standard python truth value testing https://docs.python.org/2.4/lib/truth.html . 我们可以使用标准的python真值测试https://docs.python.org/2.4/lib/truth.html

if Identifier.where:
    #Logic if where is not None.

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

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