python - 项目和属性之间的区别 - Jinja,Python

标签 python attributes jinja2 items

我正在阅读 templates in Jinja ,尤其是关于变量。我想请你解释一下这句话,关于访问传递给 Jinja 语法对象的值:

Implementation

For the sake of convenience, foo.bar in Jinja2 does the following things on the Python layer:

  • check for an attribute called bar on foo (getattr(foo, 'bar'))

  • if there is not, check for an item 'bar' in foo (foo.__getitem__('bar'))

  • if there is not, return an undefined object.

foo['bar'] works mostly the same with a small difference in sequence:

  • check for an item 'bar' in foo. (foo.__getitem__('bar'))

  • if there is not, check for an attribute called bar on foo. (getattr(foo, 'bar'))

  • if there is not, return an undefined object.

This is important if an object has an item and attribute with the same name. Additionally, the attr() filter only looks up attributes.



项目和属性有什么区别?

PS - 如果相关:我在研究字典。我刚刚读到 Jinja可以使用键作为属性(dict.key)访问值,但是在阅读有关进程顺序的这一部分后,我感到困惑。比较“键值”对使得理解上面的部分更具挑战性。

最佳答案

在 python 类中 实例 有属性;字典包含 项目 .
dict项是键和值的组合

a = object()
a.attribute = 'value'
b = dict()
b['key'] = 'value'
b.items()

关于python - 项目和属性之间的区别 - Jinja,Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59589889/

相关文章:

python - 检查一个字符串是否至少包含列表中的一个字符串

python - 如果满足Python中的标准,则有效地替换元素

python - pyomo + reticulate error 6 句柄无效

python - Chaco Legend 中的自定义标签

javascript - 如何在每个类中找到 href 属性?

C++ [[gnu::visibility ("default")]] 与 Windows 和 Linux 上的 __declspec(dllexport)

mysql/工作台 : why is on update CURRENT_TIMESTAMP added for not null timestamp

Python WTForms : How to dynamically set options of a SelectField in FieldList of FormFields?

javascript - 如何在 Flask 中构造动态 javascript 创建?

google-app-engine - “ self ”未定义,jinja2,appengine