cnguyen
Posts: 12
Joined: Thu Mar 27, 2014 4:18 pm

Array of functions

Mon Oct 06, 2014 3:20 pm

How do I define an array of functions in python? I'm using pyqt and have 20 buttons I need to define.

buttons[25]

def buttons[1]():
button[1].setText("Button")
def button[2]():
button[2].setText("Button")
def button[3]():
button[3].setText("Button")
and on and on.

I just want to do all the def in a single loop.

User avatar
r3d4
Posts: 984
Joined: Sat Jul 30, 2011 8:21 am
Location: ./

Re: Array of functions

Mon Oct 06, 2014 4:24 pm

try looking/searching for 'dynamic function definition python' for more examples

I used

Code: Select all

def mk_FN(value_x):
    def _fn():
        print value_x
    return _fn

fn = {}

for i in range(25):
    # print(i)    
    fn[i] = mk_FN(i);
    

# test it works 
fn[0]()
fn[1]()
fn[24]()
and tested it @ http://repl.it/languages/Python

It looks like it works to me
How it works #AFAIK

mk_FN - a function that returns _fn() functions !

fn = {} - a list[array] to store the functions

for i in range(25): - loop over range

fn = mk_FN(i); - call mk_FN() function and assign the function it returns to the fn list array .
Last edited by r3d4 on Sun Feb 26, 2017 9:38 am, edited 1 time in total.

cnguyen
Posts: 12
Joined: Thu Mar 27, 2014 4:18 pm

Re: Array of functions

Tue Oct 07, 2014 1:11 pm

Awesome. Works great

cnguyen
Posts: 12
Joined: Thu Mar 27, 2014 4:18 pm

Re: Array of functions

Tue Oct 07, 2014 3:03 pm

Here's my final code using pyqt.

Code: Select all

self.infoButtonArray=[]

for x in range(25):
      self.infoButtonArray.append(QPushButton(" ",self))

#array of 25 def functions used to link to 25 QPushButtons
def mk_FN(value):
    def _fn():
        control_window.displayInfo(value) #this function just displays button number
    return _fn

buttonPushed={}

for i in range(25):
    buttonPushed[i]=mk_FN(i)
Last edited by cnguyen on Tue Oct 07, 2014 3:05 pm, edited 1 time in total.

User avatar
r3d4
Posts: 984
Joined: Sat Jul 30, 2011 8:21 am
Location: ./

Re: Array of functions

Tue Oct 07, 2014 3:05 pm

cnguyen wrote:Here's my final code using pyqt.
Thaks! :ugeek: glad it worked , happy to help !

Return to “Python”