Python. How to call a function from a dictionary? [duplicate] - python

This question already has an answer here:
What does <function at ...> mean [duplicate]
(1 answer)
Closed 4 years ago.
I want to have a dictionary where a certain key calls a value... that value is a function and I would want that function to execute.
Below is my attempt to do it but all I get is the value of where it is stored in memory.
class Testing:
def __init__(self):
self.method = {'Method1': self.another, 'Method2': self.there}
def launch(self, input):
print(self.method[input])
#staticmethod
def another():
print('This print statement should pop out.')
#staticmethod
def there():
print('This should not appear.')
new = Testing()
new.launch('Method1')
The result that I get from that is:
<function Testing.another at 0x01519540>
Is there a way to do this?

You are missing the actual function call: (notice the added () at the end)
def launch(self, input):
print(self.method[input]())

Related

Executing objects using dictionaries in Python [duplicate]

This question already has answers here:
Python Argument Binders
(7 answers)
Is there a way to store a function in a list or dictionary so that when the index (or key) is called it fires off the stored function?
(3 answers)
Closed 1 year ago.
I am kind of stuck using custom class objects within dictionaries.
These are my classes, they work just fine.
from sqllibrary import cursor
from cloudlib import upload
class Mycustomconf(object):
def __init__(self):
self.cursor = cursor(foo, bar)
class Mycustomclass1(Mycustomconf):
def __init__(self):
super().__init__()
def something_useful(self, something):
self.upload(self.cursor(f'''SELECT foo FROM bar WHERE id = {something};'''))
def something_useful_too(self, something):
self.upload(self.cursor(f'''SELECT foo FROM bar WHERE id = {something};'''))
class Mycustomclass2(Mycustomconf):
def __init__(self):
super().__init__()
def something_useful(self, something):
self.upload(self.cursor(f'''SELECT foo FROM bar WHERE id = {something};'''))
def something_useful_too(self, something):
self.upload(self.cursor(f'''SELECT foo FROM bar WHERE id = {something};'''))
mcc1 = Mycustomclass1()
mcc2 = Mycustomclass1()
I want to execute one of the methods of each class (Mycustomclass1, Mycustomclass2) based on a condition. I can achieve that with the following script.
from foobar import mcc1, mcc2
def handler(foo, bar):
try:
mcc1.something_useful('42', '23')
except error1 as er:
mcc1.something_useful_too('42', '22', '11')
try:
mcc2.something_useful('42', 42, '23', 12)
except error1 as er:
mcc2.something_useful_too(42, '23', 12)
...
handler(foo, bar)
That pattern is exactly the same in all the class methods I want to execute (Try "something_useful" except error execute "something_useful_too").
The thing is, I've been trying for a while but I am unable to get the same functionality as the previous code but avoiding that redundant try-except blocks over and over again.
Here is the last thing I've tried before posting:
from foobar import mcc1, mcc2
dict = {"task_a": (mcc1.something_useful('42'),
mcc1.something_useful_too('42')),
"task_b": (mcc2.something_useful('42'),
mcc2.something_useful_too('42'))}
def handler(foo, bar):
for key in dict.keys():
try:
dict[key][0]
except error1 as er:
dict[key][1]
handler(foo, bar)
The new handler function is much slower for an unknown reason. It appears to call the methods more than once within the for loop but I don't know why is slower that way.
Thanks for correct this error in the comments
I think there might be a cleaner way to perform this that I am not seeing right now. Can anyone post a cleaner approach than mine?
Thank you in advance!
Currently the methods will be evaluated when the dictionary is declared. You could instead store the options as tuples of function reference and parameter value:
from foobar import mcc1, mcc2
dict = {"task_a": ((mcc1.something_useful, '42')),
(mcc1.something_useful_too, '42')),
"task_b": ((mcc2.something_useful, '42'),
(mcc2.something_useful_too, '42'))}
def handler(foo, bar):
for key in dict.keys():
try:
dict[key][0](dict[key][1])
except error1 as er:
dict[key][1](dict[key[1])
handler(foo, bar)

Extra "None" as output in python [duplicate]

This question already has answers here:
Why is "None" printed after my function's output?
(7 answers)
Closed 4 years ago.
class student:
birth_day = 21
birth_month = 4
birth_year = 1998
def __init__(self,name):
self.naav = name
def SayHi(self):
return print('hello'+''+self.naav)
Topper = student('vikas')
print(Topper.naav)
print(Topper.SayHi())
print(student.birth_day)
print(Topper.birth_day)
#print(student.naav)
The output to this is
vikas
hellovikas
None
21
21
I am confused with third output "None",am not sure how it works ,somebody help me understand
This is happening because on print(Topper.SayHi()) you are printing what the function SayHi returns, which is nothing (None).
This is because print('hello'+''+self.naav) doesn't return a value, it prints and returns nothing.
What you should do is return only the string, then print the return of the function SayHi (as you're already doing).
class student:
...
def SayHi(self):
return 'hello' + self.naav
...
print(Topper.SayHi())

Python pass in function as argument, print the function name and results [duplicate]

This question already has answers here:
How to get a function name as a string?
(14 answers)
Closed 4 years ago.
If I want to pass a function func1 as argument in another function, but want to return the function name, what shall I do?
let say
def func1(x):
return x**2
def main_function(func1,x):
.....
return ___(name of func1),value of func1(x)___
which means I want things like:
func_name, result = main_function(func1,2)
print(func_name)
func1
print(result)
4
def func1(x):
return x**2
def main_function(f,x):
print('f name=', f.__name__)
print('f value=', f(x))
main_function(func1, 5)
output is
f name= func1
f value= 25
Try this:
def main_function(f, x):
return f.__name__, f(x)
Just use __name__ to get function name as str.
def main_function(func, x):
# do something else
return func.__name__, func(x)

Calling out a function, not defined error [duplicate]

This question already has answers here:
How can I call a function within a class?
(2 answers)
Closed 3 years ago.
I'm new to making classes and I'm trying to complete exercise 9-1 in my 'Python Crash Course' book where the last part of the question asks me to call back my method but I end up getting
'not defined error' for describe_restaurant().
Here is my code:
class Restaurant():
def __init__(self, r_name, c_type):
self.r_name = r_name
self.c_type = c_type
def describe_restaurant():
print(self.r_name.title())
print(self.c_type.title())
def open_restaurant():
print(self.r_name + " is now open!")
Restaurant = Restaurant('Joe\'s Sushi', 'sushi')
print(Restaurant.r_name)
print(Restaurant.c_type)
describe_restaurant()
open_restaurant()
I thought that describe_restaurant shouldn't need to be defined though because I'm calling it out as a function to use?
Try:
class Restaurant():
def __init__(self, r_name, c_type):
self.r_name = r_name
self.c_type = c_type
def describe_restaurant(self):
print(self.r_name)
print(self.c_type)
def open_restaurant(self):
return "{} is now open!".format(self.r_name)
restaurant = Restaurant('Joe\'s Sushi', 'sushi')
print(restaurant.r_name)
print(restaurant.c_type)
restaurant.describe_restaurant()
restaurant.open_restaurant()
You need to create a class instance and call it's functions. In addition, as mentioned in the comments, you need to pass self to the instance methods. A short explanation of this can be found here.

Returning a function in Python [duplicate]

This question already has answers here:
Interesting 'takes exactly 1 argument (2 given)' Python error
(6 answers)
Closed 6 years ago.
I get the following error "TypeError: make_pretty() takes exactly 1 argument (2 given)" for the below code snippet. I'm learning python and any help would be helpful...
class test:
def make_pretty(func):
def inner():
print("I got decorated")
func()
return inner
def ordinary():
print("I am ordinary")
pretty1 = test()
pretty = pretty1.make_pretty(pretty1.ordinary)
print(pretty())
I also tried it with decorators, but still face the same error..
class SmartDivide:
def smart_divide(self,func):
def inner(a,b):
print("I am going to divide",a,"and",b)
if b == 0:
print("Whoops! cannot divide")
return
return func(a,b)
return inner
#smart_divide
def divide(self,a,b):
return a/b
dvd = SmartDivide()
print(dvd.divide(2,5))
dvd.divide(2,0)
You may need the self keyword
class test:
def make_pretty(self, func):
def inner():
print("I got decorated")
func()
return inner
def ordinary(self):
print("I am ordinary")
pretty1 = test()
pretty = pretty1.make_pretty(pretty1.ordinary)
print(pretty())

Categories

Resources