gpt4 book ai didi

python - 在上下文中评估变量

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

假设我有一个 django 上下文 C 并且我想在 C 中计算变量 var (不处理模板),该怎么办?

class PersonClass: pass
p = PersonClass
p.name = 'Test'

C = Context({"person": p})
# let's say I want to evaluate person.name

evaluate(C, 'person.name') should give 'Test' # like {{person.name}} in template would give Test

最佳答案

这行得通吗:

>>> C = Context({"person": p})
>>> C.get("person")
<class '__main__.PersonClass'>
>>> C.get("person").name
'Test'

编辑:更通用的版本:

def get_attr_from_context(ctx, attr_str):
attrs = iter(attr_str.split('.'))
ans = ctx.get(next(attrs))
for attr in attrs:
ans = getattr(ans, attr)
return ans

# Prints 'Test'
print(get_attr_from_context(C, 'person.name'))

关于python - 在上下文中评估变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33431989/

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