从函数传递变量以在其他函数中访问 [Python]

Passing a variable from a function to be acessible in other function [Python]

我最近刚进入 python 世界,我正在为一个问题而苦苦挣扎...

我正在做一个连接到 raspberry pi 中的数据库的应用程序(它总是在改变它的 ip,而 android 手机无法解析它的主机名,这就是为什么我需要指定地址)。

我目前正在使用 Python 3.9 和 Kivy 2.0.0。

我希望 variavel 函数中的那两个变量(mydbmycursor)可以在其他函数中访问...我有什么办法吗这个?

Main.py

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.gridlayout import GridLayout
from kivy.properties import StringProperty
from kivy.uix.label import Label
from kivy.uix.popup import Popup
import mysql.connector

class MainWidget2(BoxLayout):

    server_connect = StringProperty("not_connected.png")
    debug_net = StringProperty()
    hosts = StringProperty()
    input_text = StringProperty()
    def variavel(self, widget):
        self.hosts= widget.text
        widget.text = ""
        try:
            mydb = mysql.connector.connect(host=str(self.hosts), user="client", passwd="", database="skye_pap")
            mycursor = mydb.cursor()
            self.server_connect = 'connected.png'
        except Exception as a:
            self.debug_net = str(a)
            self.server_connect = 'not_connected.png'

    def frente(self):
        try:
            mydb = mysql.connector.connect(host=str(self.hosts), user="client", passwd="afonso11", database="skye_pap")
            mycursor = mydb.cursor()
            mycursor.execute('UPDATE car_controll SET motor=1')
            mydb.commit()
        except Exception as b:
            
            pass
    def tras(self):
        mydb = mysql.connector.connect(host=str(self.ids["input"].text), user="client", passwd="afonso11", database="skye_pap")
        mycursor = mydb.cursor()
        try:
            mycursor.execute('UPDATE car_controll SET motor=-1')
            mydb.commit()
        except Exception as b:
            pass
    def esq(self):
        try:
            self.mycursor.execute('UPDATE car_controll SET servo=1')
            self.mydb.commit()
        except Exception as b:
            pass
    def dir(self):
        try:
            self.mycursor.execute('UPDATE car_controll SET servo=2')
            self.mydb.commit()
        except Exception as b:
            pass
    def meio(self):
        try:
            self.mycursor.execute('UPDATE car_controll SET servo=0')
            self.mydb.commit()
        except Exception as b:
            pass
    def meio_motor(self):
        try:
            self.mycursor.execute('UPDATE car_controll SET motor=0')
            self.mydb.commit()
        except Exception as b:
            pass
    def lights_on(self, onemore, state):
        if state == "down":
            print("on")
            try:
                self.mycursor.execute('UPDATE car_controll SET luz=1')
                self.mydb.commit()
            except Exception as z:
                pass
        else:
            print("off")
            try:
                self.mycursor.execute('UPDATE car_controll SET luz=0')
                self.mydb.commit()
            except Exception as z:
                pass
        

class skye(App):
    def build(self):
        self.icon = "logoapp.png"

skye().run()

skye.kv

MainWidget2:

<MainWidget2>:
    GridLayout:
        cols:3
        GridLayout:#botoes esquerda
            padding: ("50dp","30px","0px","0px")
            pos: self.parent.pos
            cols: 3
            Button:
                text: "0"
                size_hint: None,None
                size: "70dp", "70dp"
                disabled: True
                opacity: 0
                    
            Button:
                text: "B1"
                size_hint: None,None
                size: "100dp", "100dp"
                background_normal: 'desligado.png'
                background_down: 'ligado2.png'
                on_press: root.frente()
                on_release: root.meio_motor()

            Button:
                text: "0"
                size_hint: None,None
                size: "70dp", "70dp"
                disabled: True
                opacity: 0

            Button:
                text: "B2"
                size_hint: None,None
                size: "70dp", "70dp"
                disabled: True
                opacity: 0
        
            Button:
                text: "0"
                size_hint: None,None
                size: "70dp", "70dp"
                disabled: True
                opacity: 0
                
            Button:
                text: "B3"
                size_hint: None,None
                size: "70dp", "70dp"
                disabled: True
                opacity: 0


            Button:
                text: "0"
                size_hint: None,None
                size: "70dp", "70dp"
                disabled: True
                opacity: 0
                
            Button:
                text: "B4"
                size_hint: None,None
                on_press: root.tras()
                on_release: root.meio_motor()
                size: "100dp", "100dp"
                background_normal: 'desligado.png'
                background_down: 'ligado2.png'

            Button:
                text: "0"
                size_hint: None,None
                size: "70dp", "70dp"
                disabled: True
                opacity: 0

        GridLayout:
            cols: 1
        
            Image:
                source: root.server_connect
                size_hint: .8, .8
                id:server_status
            FloatLayout:
                ToggleButton:
                    pos_hint: {'center_x': .5, 'center_y': .5}
                    id: luzes_toggle
                    size_hint: None, None
                    size: "100dp", "100dp"
                    background_normal: 'luz_desligada.png'
                    background_down: 'luz_ligada.png'
                    on_state: root.lights_on(self, self.state)
                
            Label:
                text: root.debug_net
            TextInput:
                id: input
                multiline: False
                on_text_validate: root.variavel(self)
                text: root.input_text
            Label:
                text: root.hosts
            Button:
                text:"Falar"
            Label:
                text: "Luzes:"
            
        GridLayout:#botoes direita
            cols: 3
            padding: ("0dp","30px","50px","0px")
            Button:
                text: "0"
                size_hint: None,None
                size: "70dp", "70dp"
                disabled: True
                opacity: 0
                
                    
            Button:
                text: "B1"
                size_hint: None,None
                size: "70dp", "70dp"
                disabled: True
                opacity: 0

            Button:
                text: "0"
                size_hint: None,None
                size: "70dp", "70dp"
                disabled: True
                opacity: 0

            Button:
                text: "B2"
                size_hint: None,None
                size: "100dp", "100dp"
                background_normal: 'desligado.png'
                background_down: 'ligado2.png'
                on_press: root.esq()
                on_release: root.meio()
        
            Button:
                text: "0"
                size_hint: None,None
                size: "70dp", "70dp"
                disabled: True
                opacity: 0
                
            Button:
                text: "B3"
                size_hint: None,None
                size: "100dp", "100dp"
                background_normal: 'desligado.png'
                background_down: 'ligado2.png'
                on_press: root.dir()
                on_release: root.meio()

            Button:
                text: "0"
                size_hint: None,None
                size: "70dp", "70dp"
                disabled: True
                opacity: 0
                
            Button:
                text: "B4"
                size_hint: None,None
                size: "70dp", "70dp"
                disabled: True
                opacity: 0
                
            Button:
                text: "0"
                size_hint: None,None
                size: "70dp", "70dp"
                disabled: True
                opacity: 0


            
    

您应该在每个您希望从 object 中的每个 method 访问的变量之前添加 self.

例如,将每个 mydb 变量设为 self.mydb,将 mycursor 设为 self.mycursor

要提升方法范围的变量以供其他 class 方法使用,请将它们添加到 self:

self.mydb = mysql.connector.connect(...[stuff]...)
self.mycursor = self.mydb.cursor()

然后将所有对 mydb 的引用替换为 self.mydb,将对 mycursor 的所有引用替换为 self.mycursor。这些变量可以从相同 class.

的其他方法访问

在 class Mainwidget2 中创建 class 变量 - 让它们命名为:class_my_db、class_my_cursor.

class MainWidget2(BoxLayout):

server_connect = StringProperty("not_connected.png")
debug_net = StringProperty()
hosts = StringProperty()
input_text = StringProperty()
class_my_db = '' //New Class Variable to hold my_db
class_my_cursor = '' //New Class Variable to hold my_cursor

现在您可以在通读 mysql 后设置 class 变量的值。

def variavel(self, widget):
    self.hosts= widget.text
    widget.text = ""
    try:
        mydb = mysql.connector.connect(host=str(self.hosts), user="client", passwd="", database="skye_pap")
        self.class_my_db = mydb //assigning mydb to the class variable
        mycursor = mydb.cursor()
        self.class_my_cursor = mycursor //assigning mydb to the class variable
        self.server_connect = 'connected.png'
    except Exception as a:
        self.debug_net = str(a)
        self.server_connect = 'not_connected.png'

现在您可以使用 self 运算符访问所有其他函数中的 class 变量。 self.class_my_dbself.class_my_cursor 就足够了。