gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 01:35:49 24 4
gpt4 key购买 nike

我正在阅读 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com