calling function from string with the function’s name

By | 2017/03/04

calling function from string with the function’s name

<br />class Uploader(object):
    def __init__(self, by):
        super(Uploader, self).__init__()
        self.by = by

    def by_ftp(self, name="ftp"):
        print "name is %s, by: %s" % (name, self.by)
        return "FTP"

    def by_http(self, name="http"):
        print "name is %s, by: %s" % (name, self.by)
        return "HTTP"

    def upload(self):
        result = getattr(self, "by_%s" % self.by)(name="http")
        print result

if __name__ == "__main__":
    u = Uploader("ftp")
    u.upload()

http://stackoverflow.com/questions/3061/calling-a-function-of-a-module-from-a-string-with-the-functions-name-in-python

Leave a Reply

Your email address will not be published. Required fields are marked *