Home > Mobile >  Python get parameter outside of class
Python get parameter outside of class

Time:05-27

I have this code :

class X(object):
    def func1(self, arg):
        print("Button {0} clicked".format(arg))
        return True

class Y(X):
    def func2(self):
       self.btn = QPushButton()
       self.btn.clicked.connect(partial(self.func1 , True ) )

#while func1 ==True :
       #do something
 

When I press the button, the arg parameter will be set to True.

I wish I could call function 1 outside of class, which will only be true if the button is pressed.

CodePudding user response:

If you have to do something when you click button then you should do it directly inside func1.

But if you want to set some value which will be used later then you should use self.value to keep this value inside instance of this class - and later other function should get this value - without running function

class X(object):
    
    def __init__(self):
        self.value = False   # set default value at start
        
    def func1(self, arg):
        print("Button {0} clicked".format(arg))
        self.value = True    # change value when click

class Y(X):
    def func2(self):
       self.btn = QPushButton()
       self.btn.clicked.connect(partial(self.func1, True))

# create instance of class

x = Y()

# access value in instance

while x.value is True:
   #do something

But while-loop may block event-loop in GUI and it may freeze GUI so it may need to run while-loop inside thread. Or it may need some timer to execute function periodically without loop and without thread.

class X(object):
    
    def __init__(self):
        self.value = False   # set default value at start
        self.thread = None   # set default value at start
        
    def func1(self, arg):
        print("Button {0} clicked".format(arg))
        self.value = True    # change value when click

        if self.thread != None:
            print("thread already running")
        else:
            self.thread = threading.Thread(taget=self.long_running_loop)
            self.thread.start()
        
    def long_running_loop(self):
        while self.value is True:
             #do something
        self.thread = None   # inform function that it can run it again
        
class Y(X):
    def func2(self):
       self.btn = QPushButton()
       self.btn.clicked.connect(partial(self.func1, True))

# create instance of class

x = Y()

I show example with standard Thread but PyQt has own class QThread which you should use.

  • Related