是否有类似于php的$$ variable在python中的语法 [英] is there similar syntax to php's $$variable in python

查看:37
本文介绍了是否有类似于php的$$ variable在python中的语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在python中是否有与php的$$ variable类似的语法?我实际上正在尝试的是基于值加载模型.

is there similar syntax to php's $$variable in python? what I am actually trying is to load a model based on a value.

例如,如果值为Song,我想导入Song模块.我知道我可以使用if语句或lambada,但是类似于php的$$ variable会更方便.

for example, if the value is Song, I would like to import Song module. I know I can use if statements or lambada, but something similar to php's $$variable will be much convenient.

我追求的是与此类似的东西.

what I am after is something similar to this.

from mypackage.models import [*variable] 

然后在视图中

def xyz(request): 
    xz = [*variable].objects.all() 

* variable是在设置中定义的值或可以来自命令行.它可以是项目中的任何模型.

*variable is a value that is defined in a settings or can come from comandline. it can be any model in the project.

推荐答案

def load_module_attr (path):
    modname, attr = path.rsplit ('.', 1)
    mod = __import__ (modname, {}, {}, [attr])
    return getattr (mod, attr)

def my_view (request):
    model_name = "myapp.models.Song" # Get from command line, user, wherever
    model = load_module_attr (model_name)
    print model.objects.all()

这篇关于是否有类似于php的$$ variable在python中的语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆