【问题标题】:Python/Django creating several classes from variable through loopingPython/Django 通过循环从变量创建几个类
【发布时间】:2020-04-16 23:04:17
【问题描述】:

我正在使用 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)。我怎样才能通过循环来做到这一点?我想避免上三门课。

【问题讨论】:

    标签: python django class view


    【解决方案1】:

    创建三个不同的类来做同样的事情不符合DRY philosophy

    为什么不创建一个带有参数的类,并使用该参数来获得您想要的特定行为?

    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(),但您可以向其传递该类用于设置模板的参数...类似这样:

    urls.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')),
    ]
    

    views.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,b.html 请求b url,等等...

    【讨论】:

    • 看起来不错,但现在我正在为 urls.py 苦苦挣扎,因为 a、b、c 是类实例。如何将其传递给 URL 而不会出错?通常我会执行以下操作: CBV 的 path('a/', views.a) 或 path('a/', views.a.as_view()) 但它不适用于类实例,我还没有找到任何答案如何弄清楚
    • @sebastian 编辑了我的答案,如果有帮助请告诉我
    • 是的,完全正确。非常简单明了的解决方案,非常感谢。
    猜你喜欢
    • 1970-01-01
    • 2012-06-01
    • 1970-01-01
    • 2016-01-11
    • 2020-06-05
    • 1970-01-01
    • 2021-12-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多