python - Python/Django 通过循环从变量创建几个类
问题描述
我正在使用 Python Django,并且正在尝试创建一个包含多个子页面的论坛 - 每个子页面都涉及另一个主题,并且应该看起来相同但存储不同的帖子。我想创建几个具有相似名称和相同属性的类(不是实例!)。每个类都应该有另一个模板名称并呈现其他帖子。像这样的东西:
my_variable = 'part_of_class_name'
for class_number in range(2, 5):
class_name = my_variable + str(class_number) + '(SameParentClass)'
class class_name:
template_name = 'template' + str(class_number) + '.html'
当然,上面的代码不起作用,是否可以将变量传递给类名?我想要以下内容:part_of_class_name2(SameParentClass)、part_of_class_name3(SameParentClass)、part_of_class_name4(SameParentClass)。我怎样才能通过循环来做到这一点?我想避免上三门课。
解决方案
制作三个做同样事情的独立类不符合DRY 哲学
为什么不创建一个带有参数的类,并使用该参数来获得您想要的特定行为?
class ClassName:
def __init__(self, class_number):
self.template_name = 'test' + str(class_number) + '.html'
a = ClassName(1)
b = ClassName(2)
c = ClassName(3)
print(a.template_name)
print(b.template_name)
print(c.template_name)
回报:
test1.html
test2.html
test3.html
根据您的评论进行编辑 - 您不能调用as_view()
instance ,但您可以将其传递给该类用于设置模板的参数......像这样:
网址.py:
from django.urls import path
from .views import ForumView
urlpatterns = [
path('a', ForumView.as_view(template_name='a')),
path('b', ForumView.as_view(template_name='b')),
path('c', ForumView.as_view(template_name='c')),
]
视图.py:
from django.template.response import TemplateResponse
from django.views.generic.base import View
class ForumView(View):
template_name = None
def get(self, request, *args, **kwargs):
return TemplateResponse(request, self.template_name + '.html')
这将加载a.html
对a
url、 url 等b.html
的请求b
......
推荐阅读
- reactjs - “无法读取未定义的属性‘切片’”在 onClick 处理程序中
- upload - 如何通过优酷授权我的应用程序将视频上传到最终用户的帐户?
- python - 如何解析在python中可能包含或不包含换行符的字符串?
- javascript - 在移动视图中将按钮更改为 dropdwon
- java - 制作内部列表的键与外部列表的值
- amazon-web-services - 创建服务目录我是 cloudformation 模板中的角色
- json - 如何从bash填充/更改格式良好的JSON文件的某些部分的特定未知字符串,保持格式不变?
- r - 我可以按数字类型对全球环境进行排序并将所有内容提取到一个 CSV 中吗?或者直接在 R 中从每列中的 500 多个值中创建一个数据表?
- python - 带有双引号python的熊猫查询
- c# - 我无法从 Sitefinity CMS 导出/导入菜单下载 ZIP 文件