Home Python produce function names from string
Reply: 2

Python produce function names from string

user58925
1#
user58925 Published in 2017-12-06 10:15:41Z

I would like to use functions based on strings passed in argument as below. The code gives the following error: AttributeError: 'Obj' object has no attribute 'funA'

The functions funA and funB are defined within fun because they are only used within fun and nowhere else

class Obj(object):
    def __init__(self):
        self.A = 2
        self.B = 3

    def fun(self, ar):
        def funA(self):
            print self.A

        def funB(self):
            x = self.B + 4
            print self.B

        for letter in ar:
            name = 'fun' + letter
            getattr(self, name)()

obj_instance = Obj()
obj_instance.fun(['A', 'B'])
Tobias Scheck
2#
Tobias Scheck Reply to 2017-12-06 10:35:06Z

As an alternative you can try the following code. It gives you the opportunity to check whether a function exists or not.

class Obj(object):
    def __init__(self):
        self.A = 2
        self.B = 3

    def fun(self, ar):
        def funA():
            print self.A

        def funB():
            x = self.B + 4
            print self.B
            print x

        for letter in ar:
            name = 'fun' + letter
            if name in locals():
                locals()[name]()

obj_instance = Obj()
obj_instance.fun(['A', 'B'])
XaMi
3#
XaMi Reply to 2017-12-06 10:29:39Z

I wouldn't recommend it, but if you really need it, then you can do it this way:

class Obj(object):
    def __init__(self):
        self.A = 2
        self.B = 3

    def fun(self, ar):
        def funA(self):
            print self.A

        def funB(self):
            x = self.B + 4
            print self.B

        for letter in ar:
            name = 'fun' + letter + '()'
            exec(name)

obj_instance=Obj()
obj_instance.fun(['A', 'B'])

exec() executes any string that you put in parentheses as if it was python code.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.306985 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO