首页 > 解决方案 > 我如何从 1 def 到同一类中的另一个值?

问题描述

我在高中的最后一年制作了一个对象检测应用程序,但遇到了一些麻烦。我正在寻找一种方法来使用来自 def verify 的字符串 username 在另一个 def 中,例如 Change。我已经尝试将其设为全局并将用户名从我的 kV 文件海峡发送到更改 def,但它们都不起作用。这是我的代码。

class GipApp(MDApp):
    def build(self):
        self.theme_cls.primary_palette = 'Blue'
        screen = Builder.load_string(screen_helper)

        return screen

    def verify(self, username, password):
        if username != "" and password != "":
            for row in MySqlNames:
                if row[0].strip() == username:
                    sql = "SELECT Password from ID191774_6itn1project7.Users where Username = %s "
                    mycursor.execute(sql, (username))
                    TestPassword = mycursor.fetchall()
                    for row3 in TestPassword:
                        if row3[0].strip() == password:
                            print("inloggen is gelukt")
                            sm.current_screen = 'Main'
                            return
                        if row3[0] != password:
                            dialog = MDDialog(title="Passwords is not correct.")
                            dialog.open()

        else:
            dialog = MDDialog(title="Fill in the empty text boxes")
            dialog.open()


    def register(self, RegUsername, RegPassword, RegRepeatPassword):
        if RegPassword != "" and RegRepeatPassword != "" and RegUsername != "":
            if RegPassword == RegRepeatPassword:
                current_datetime = datetime.now()
                insert = "INSERT INTO Users(Username, Password, DateOfRegistration) VALUES (%s,%s,%s)"
                mycursor.execute(insert, (RegUsername, RegPassword, current_datetime))
                conn.commit()
                dialog = MDDialog(title="You are successfully registered")
                dialog.open()
            if RegRepeatPassword != RegPassword:
                dialog = MDDialog(title="Passwords are not the same. Please try again.")
                dialog.open()
                print(MySqlNames)
        else:
            dialog = MDDialog(title="Fill in the empty text boxes")
            dialog.open()

    def Yolo(self):
        cap = cv.VideoCapture(0)
        whT = 320
        confThreshold = 0.4
        nmsThreshold = 0.2

        classesFile = "coco.names"
        classNames = []
        with open(classesFile, 'rt') as f:
            classNames = f.read().rstrip('\n').split('\n')
        print(classNames)

        modelConfiguration = "yolov3.cfg"
        modelWeights = "yolov3.weights"
        net = cv.dnn.readNetFromDarknet(modelConfiguration, modelWeights)
        net.setPreferableBackend(cv.dnn.DNN_BACKEND_OPENCV)
        net.setPreferableTarget(cv.dnn.DNN_TARGET_CPU)

        def findObjects(outputs, img):
            hT, wT, cT = img.shape
            bbox = []
            classIds = []
            confs = []
            for output in outputs:
                for det in output:
                    scores = det[5:]
                    classId = np.argmax(scores)
                    confidence = scores[classId]
                    if confidence > confThreshold:
                        w, h = int(det[2] * wT), int(det[3] * hT)
                        x, y = int((det[0] * wT) - w / 2), int((det[1] * hT) - h / 2)
                        bbox.append([x, y, w, h])
                        classIds.append(classId)
                        confs.append(float(confidence))

            indices = cv.dnn.NMSBoxes(bbox, confs, confThreshold, nmsThreshold)

            for i in indices:
                i = i[0]
                box = bbox[i]
                x, y, w, h = box[0], box[1], box[2], box[3]
                # print(x,y,w,h)
                cv.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2)
                cv.putText(img, f'{classNames[classIds[i]].upper()} {int(confs[i] * 100)}%',
                           (x, y - 10), cv.FONT_HERSHEY_SIMPLEX, 0.6, (255, 0, 0), 2)

                DetectedName = (f'{classNames[classIds[i]].upper()}')
                DetectedProcent = (f'{int(confs[i] * 100)}%')
                print(DetectedName)
                print(DetectedProcent)
                current_datetime = datetime.now()
                print(current_datetime)
                insert = "INSERT INTO DetectedObjects (WayOfDetection, ObjectName, Certainty, TimeOfDetection) VALUES (%s,%s,%s,%s)"
                mycursor.execute(insert, ("webcam", DetectedName, DetectedProcent, current_datetime))
                conn.commit()


        while True:
            success, img = cap.read()

            blob = cv.dnn.blobFromImage(img, 1 / 255, (whT, whT), [0, 0, 0], 1, crop=False)
            net.setInput(blob)
            layersNames = net.getLayerNames()
            outputNames = [(layersNames[i[0] - 1]) for i in net.getUnconnectedOutLayers()]
            outputs = net.forward(outputNames)
            findObjects(outputs, img)

            cv.imshow('Image', img)
            key = cv.waitKey(1)
            if key == 27:
                break

    def Change(self, Password, PasswordReg, username):
        if Password != "" and PasswordReg != "":
            if Password == PasswordReg:
                insert = "UPDATE `Users` SET `Password`= %s where Username = %s "
                mycursor.execute(insert, (PasswordReg, username))
                conn.commit()
                dialog = MDDialog(title="The password has been changed.")
                dialog.open()
            if Password != PasswordReg:
                dialog = MDDialog(title="New passwords are not the same. Please try again.")
                dialog.open()
                print(MySqlNames)
        else:
            dialog = MDDialog(title="Fill in the empty text boxes")
            dialog.open()

我希望有人能帮助我。

标签: pythonpython-3.x

解决方案


如果您知道verify()之前会调用它Change(),那么您可以self.username = usernameverify()函数内执行

在 python 中,与其他语言self.<variable name>类似this.<variable name>。该变量成为对象的实例变量,因此一旦定义,您就可以在类内部的任何地方使用它。


推荐阅读