Is there a way to set variable methods in Python?

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/"


    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")
    #I have tried this
    file_out = some_class(i,j).key_value()

    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):

One Answer

You can use getattr.

class some_class:
    def A(self):
    def B(self):
getattr(some_class(), 'A')()
getattr(some_class(), 'B')()

Correct answer by 정도유 on September 30, 2020

Add your own answers!

Related Questions

RecyclerView inside NestedScrollview alternative

5  Asked on January 29, 2021 by user1851366


Why I can not see bugs from Findbugs on SonarQube?

1  Asked on January 29, 2021 by user14260568


How to render an element within a function in React?

3  Asked on January 28, 2021 by peppa-box


3 errors on function from vue js

1  Asked on January 28, 2021 by nicolas-vanhuynegem


variadic template, Range, C++

1  Asked on January 28, 2021 by hrant-nurijanyan


AWS Lambda import module error in python

21  Asked on January 28, 2021 by nithin-k-anil


React native maps rerender on marker press

1  Asked on January 28, 2021 by enguerranws


Python: overwrite text file – string placeholder

1  Asked on January 28, 2021 by thommy-bee


Wrangling dataframes with Dplyr

1  Asked on January 28, 2021


Ask a Question

Get help from others!

© 2023 All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP