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

Infinite loop in Go

2  Asked on December 5, 2021 by uxtrejo


Why the buttons get disappeared when clicking them?

2  Asked on December 5, 2021 by kiyubi


image validation error : The profile picture must be an image

2  Asked on December 5, 2021 by akinori-kuwabara


How do you pass props through react router?

1  Asked on December 5, 2021 by aidan-paetsch


Refresh/Retrigger “Fetch” in a HTML/javascript

3  Asked on December 4, 2021 by sabrina-s


How to fix errors when doing a git commit?

1  Asked on December 4, 2021 by davidonstack


Get index of enum value typescript

2  Asked on December 4, 2021 by hlose-chauvel


create a new column to show the quintile in groupby

3  Asked on December 4, 2021 by warrior


Ask a Question

Get help from others!

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