Python 返回变量属性的对象属性值
我正在尝试设置一个调试页面,其中包含对象、对象属性名称和对象属性值的列表。我试图获取特定对象类型的特定属性的值。当我编码时,对象类型或属性都不知道 以下是我的相关章节: 在我的测试中.pyPython 返回变量属性的对象属性值,python,google-app-engine,jinja2,Python,Google App Engine,Jinja2,我正在尝试设置一个调试页面,其中包含对象、对象属性名称和对象属性值的列表。我试图获取特定对象类型的特定属性的值。当我编码时,对象类型或属性都不知道 以下是我的相关章节: 在我的测试中.py if self.request.get('objID'): qGet = self.request.get thisObj = db.get(db.Key(qGet('objID'))) template_values = { 'thisObj' : thisObj } template = JI
if self.request.get('objID'):
qGet = self.request.get
thisObj = db.get(db.Key(qGet('objID')))
template_values = { 'thisObj' : thisObj }
template = JINJA_ENVIRONMENT.get_template('objProp.html')
self.response.write(template.render(template_values))
在我的objProp.html模板中
{% if thisObj %}
<ul>List of properties
{% for p in thisObj.properties() %}
<li>{{ p }} : {{ thisObj.p }}</li>
{% endfor %}
</ul>
{% endif %}
{%if thisObj%}
属性列表
{thisObj.properties()中p的%s}
- {{p}}:{{thisObj.p}
{%endfor%}
{%endif%}
然而,由于thisObj中没有属性p,所以它总是打印出一个空值,这就是我想要打印出的,在循环中的特定点p所引用的任何属性的值
任何帮助都将不胜感激 您不应该使用
thisObj.p
,因为您没有在thisObj
中查找名称.p
在本例中不是循环中的p,而是尝试引用名为“p”的属性或方法
你应该使用
getattr(thisObj,p)
这是我开始使用的一种方法。我不会接受它,因为我还不认为它是一个“好”的方法
另见:
这个问题把我带到了那里,下面是我正在使用的,它似乎运行正常:
{% if thisObj %}
<ul>List of properties
{% for p in thisObj.properties() %}
<li>{{ p }} : {{ thisObj.properties()[p].get_value_for_datastore(thisObj) }}</li>
{% endfor %}
</ul>
{% endif %}
{%if thisObj%}
属性列表
{thisObj.properties()中p的%s}
- {{p}:{{thisObj.properties()[p].get_value_for_datastore(thisObj)}
{%endfor%}
{%endif%}
似乎p是解析为字符串,thisObj.properties()[p]
返回对象属性,然后我只需要使用.get\u value\u for\u datastore(thisObj)
从这里的文档中引用:我得到一个指示,即getattr()未定义。有什么方法可以在Jinja模板中启用此功能吗?另一个答案是更好的,并且有效。我不使用jinja,所以我不知道为什么不能访问GetAttr。您可以通过使用
thisObj.properties().values()
避免[p]步骤,然后使用p.get\u value\u作为数据存储(thisObj)