我正在使用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 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