[英]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 我希望能够在具有动态函数名称的Python类上调用不同的方法,例如
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"? 什么是“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 . 我在内置函数列表中查看了
getattr
, apply
和其他内容。 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
确实似乎是你想要的:
getattr(o, "A")(1)
is equivalent to 相当于
o.A(1)
Python中的方法是一流的对象。
getattr(o, 'A')(1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.