首页 > 解决方案 > 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)。我怎样才能通过循环来做到这一点?我想避免上三门课。

标签: pythondjangoclassview

解决方案


制作三个做同样事情的独立类不符合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.htmlaurl、 url 等b.html的请求b......


推荐阅读