在Python中使用参数调用对象的方法
我希望能够使用动态函数名称调用 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
“foo”是什么? (或者还有其他方法吗?)我确信它一定存在,但我似乎找不到它或记住它叫什么。我查看了 getattr
、apply
和 列表中的其他内容内置函数。这是一个如此简单的参考问题,但是唉,我来了!
感谢您的阅读!
I want to be able to call different methods on a Python class with dynamic function name, e.g.
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
好吧,
getattr
确实似乎是你想要的:相当于
Well,
getattr
indeed seems to be what you want:is equivalent to
Python 中的方法是一等对象。
Methods in Python are first-class objects.