python - 使用相同参数重复初始化类的最佳实践(金字塔)?

标签 python class inheritance initialization dry

我想简化/减少我的代码,所以我尝试将具有重复参数的类的初始化放在它们自己的扩展类中。这是一个基于 Pyramid & Cornice 的 REST API。

我如何初始化 pyramid.httpexceptions.HTTPUnauthorized当我总是在初始化时添加相同的 header 时?这也适用于其他 HTTP 响应,我在不更改其参数的情况下重复初始化它们。

目前我想出了这个来扩展类(class):

class _401(HTTPUnauthorized):
    def basic_jwt_header(self):
        self.headers.add('WWW-Authenticate','JWT')
        self.headers.add('WWW-Authenticate', 'Basic realm="Please log in"')
        return self

    def jwt_header(self):
        self.headers.add('WWW-Authenticate','JWT')
        return self

我在这样的 View 中使用:

@forbidden_view_config()
def authenticate(request):
    response = _401()
    return _401.basic_jwt_header(response)

但是感觉和看起来都不对劲。有没有更好、更干净的方法?

最佳答案

在类上创建一个 __init__ 方法:

class _401(HTTPUnauthorized):

    def __init__(self):
        # call base class __init__ first, which will set up the
        # headers instance variable
        super(_401, self).__init__()
        # in Python 3, just use this:
        # super().__init__()

        # now add the headers that you always enter
        self.headers.add('WWW-Authenticate','JWT')
        self.headers.add('WWW-Authenticate', 'Basic realm="Please log in"')

resp = _401()
print resp.headers

关于python - 使用相同参数重复初始化类的最佳实践(金字塔)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34978749/

相关文章:

python - 如何将灰度图像转换为像素值列表?

javascript - Python 到 JavaScript unix 时间转换

python - 在类中设置默认值

c++ - 有没有办法打印当前类中复合数据类型的所有属性

java - 数组中的多态子类对象方法不起作用

python - 如何在Python中实现泛型? Java 或 C++ 之类的东西提供

python - vim:使用选定的行作为 python 函数的输入

css - 如何更改所有类的名称,特别是 div?

java - 为什么公共(public)类需要在包中而不是它自己的包中导入?

c# - 将setter添加到C#接口(interface)中继承的只读属性