I’m new to programming and I’m interested in if it’s possible to use a function to create another function based in inputted information:
def get_new_toy(self):
new_toy = gui.multenterbox(
msg = 'Enter the data for the new toy:',
title = 'New Toy',
fields = ('Toy Name', 'Fun for 0 to 5', 'Fun for 5 to 7', 'Fun for 7 to 10', 'Fun for over 10'))
method = getattr(PotatoHead, new_toy[0])
def method(self):
I don’t think that I’m doing this right
Thankful for any help
—Edit—
Sorry for not making it clear:
I’m creating a virtual pet sort of game for my younger sister.
The ‘PotatoHead’ can ‘play’ with certain toys as dictated by functions such as this:
def play_Softball(self):
self.happiness_num = float(self.happiness)
if float(self.age) <= 3.0:
self.happiness_num = self.happiness_num + 0.3
elif float(self.age) > 3.0 and float(self.age) < 4.0:
self.happiness_num = self.happiness_num + 0.7
elif float(self.age) > 4.0 and float(self.age) < 7.0:
self.happiness_num = self.happiness_num + 1.0
elif float(self.age) > 7.0 and float(self.age) < 9.0:
self.happiness_num = self.happiness_num + 0.5
elif float(self.age) > 9.0:
self.happiness_num = self.happiness_num + 0.02
gui.msgbox(
msg = 'This toy is Only providing minimal fun to your potato head. Either get a new one or play with another!',
title = 'WARNING!',
ok_button = 'Understood')
self.happiness = str(self.happiness_num)
I want there to be a function that allows the creation of a new ‘toy’ as a function that is similar to the one above.
Again, thanks for any help
—UPDATE—
Thanks again, but just wondering
Is it possible to work something such as this into it:
'play_' + new_toy[0] = myPotatoHead.create_toy(new_toy[1], new_toy[2], new_toy[3], new_toy[4], new_toy[5])
in this context:
def get_new_toy(self):
new_toy = gui.multenterbox(
msg = 'Enter the data for the new toy:',
title = 'New Toy',
fields = ('Toy Name', 'Fun for 0 to 3', 'Fun for 3 to 4', 'Fun for 4 to 7', 'Fun for 7 to 9', 'Fun for over 9'))
'play_' + new_toy[0] = myPotatoHead.create_toy(new_toy[1], new_toy[2], new_toy[3], new_toy[4], new_toy[5])
self.toys.append(new_toy[0])
thanks again for any help
Here is an example python function that returns a new function based on the parameter passed in. I’m not sure what you are trying to do but this might help point you in the right direction.
Given your toy example (which seems like a fun thing to do for you sister) you might try something like this (I haven’t tested the code, but it should help out):