传递要动态查找的成员
我想确定要动态查找哪个属性, 考虑下面的Python代码:
def f(x, a):
return x.a
class X:
b = 4
x = X()
print(f(x, b))
如果Python有这个属性,上面的代码应该打印4。
有没有办法用任何语言来做到这一点? 我无法想象使用 C++ 模板或动态类型的方法。
I want to determine which attribute to look-up dynamicaly,
Consider below python code:
def f(x, a):
return x.a
class X:
b = 4
x = X()
print(f(x, b))
If python had this property, above code should print 4.
Is there way to do it in any language?
I cannot conceive a way with C++ templates or dynamic typing.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我认为您无法以您尝试的方式动态访问对象的属性。内置函数
getattr
将允许您执行此操作。正如 marcin 建议的那样,您可以将 f 替换为getattr
http:// docs.python.org/library/functions.html#getattr
或
I don't think you can dynamically access attributes of objects in the way you are attempting. the built-in function
getattr
will allow you to do this. As marcin suggested you can just replace f withgetattr
http://docs.python.org/library/functions.html#getattr
or
在 Python 中,使用 字典
In Python, use a dictionary
f = getattr
这将使您的示例正常工作。我认为你需要阅读 python 文档: http://docs.python.org/library/functions .html
f = getattr
That will make your example work. I think you need to read the python docs: http://docs.python.org/library/functions.html