简体   繁体   中英

Call a method of an object with arguments in Python

I want to be able to call different methods on a Python class with dynamic function name, eg

class Obj(object):
    def A(self, x):
        print "A %s" % x

    def B(self, x):
        print "B %s" % x

o = Obj()

 # normal route
o.A(1) # A 1
o.B(1) # B 1

 # dynamically
foo(o, "A", 1) # A 1; equiv. to o.A(1)
foo(o, "B", 1) # B 1

What is "foo"? (or is there some other approach?) I'm sure it must exist, but I just can't seem to find it or remember what it is called. I've looked at getattr , apply , and others in the list of built-in functions . It's such a simple reference question, but alas, here I am!

Thanks for reading!

Well, getattr indeed seems to be what you want:

getattr(o, "A")(1)

is equivalent to

o.A(1)

Python中的方法是一流的对象。

getattr(o, 'A')(1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM