我通常在 python3 中使用内部类来执行此操作
class SomeSerializer():
class __Paginator(Paginator):
page_size = 10
# defining it for e.g. Rest:
pagination_class = __Paginator
# you could also be accessing it to e.g. create an instance via method:
def get_paginator(self):
return self.__Paginator()
当我使用双下划线时,这将“修改”的想法与内部类混合在一起,从外部您仍然可以使用SomeSerializer._SomeSerializer__Paginator
, 和子类访问内部类,但是 SomeSerializer.__Paginator 将不起作用,这可能是也可能不是你的愿望您希望它更“匿名”。
但是,如果您不需要修改,我建议使用带有单个下划线的“私有”表示法。
In my case, all I need is a fast subclass to set some class attributes, followed up by assigning it to the class attribute of my RestSerializer class, so the double underscore would denote to "not use it at all further" and might change to no underscores, if I start reusing it elsewhere.