Stack Overflow Asked by defarm on September 30, 2020
I would like to call a method from some_class
in a function csv_output
. However, some_class
has several methods which run different functions that are meant to be saved in .csv format. In the code I’ve written so far, I type in a string which references a dictionary of specific methods with values which are specific_method
. This is then saved as key_value
. I create a variable file_out = some_class(i,j).key_value()
. key_value
is not a method of some_class
– and that’s the exception I’m returned.
In essence, I would like to call a method, which isn’t defined in some_class
, which will reflect user input.
def csv_output(specific_method,i,j):
parent_dir = "/home/my_project/csv/"
os.chdir(parent_dir)
dir_of_types = {"1":"A()","2":"B()","3":"C()"}
key_value = dir_of_types.get(specific_method)
if specific_method not in dir_of_types.keys():
print("No such method")
print("Accepted methods are: 1,2,3")
return
else:
pass
#I have tried this
file_out = some_class(i,j).key_value()
#this
file_out = rationals_repeating(res,shift)."%s" % (key_value())
#and this
file_out = rationals_repeating(res,shift)."%s" % (key_value)
np.savetxt("%s%s/%s-%s.csv" % (parent_dir,specific_method,i,j), file_out,delimiter=',',fmt='%s')
for i in range(0,100):
csv_output("1",1000,i)
csv_output("2",1000,i)
csv_output("3",1000,i)
You can use getattr
.
class some_class:
def A(self):
print('A')
def B(self):
print('B')
getattr(some_class(), 'A')()
getattr(some_class(), 'B')()
Correct answer by 정도유 on September 30, 2020
1 Asked on December 5, 2021
2 Asked on December 5, 2021
2 Asked on December 5, 2021 by kiyubi
1 Asked on December 5, 2021 by pysql
1 Asked on December 5, 2021 by chenlin-wang
1 Asked on December 5, 2021
1 Asked on December 5, 2021 by mr-baks
2 Asked on December 5, 2021 by akinori-kuwabara
1 Asked on December 5, 2021
1 Asked on December 5, 2021 by erv
1 Asked on December 5, 2021 by aidan-paetsch
0 Asked on December 5, 2021 by pavan-ajit
3 Asked on December 4, 2021 by sabrina-s
4 Asked on December 4, 2021
3 Asked on December 4, 2021
2 Asked on December 4, 2021 by rmoore35
3 Asked on December 4, 2021 by warrior
Get help from others!
Recent Answers
© 2022 AnswerBun.com. All rights reserved. Sites we Love: PCI Database, MenuIva, UKBizDB, Menu Kuliner, Sharing RPP