如何通过继承在python中子类化请求 [英] How to subclass requests in python through inheritance

查看:57
本文介绍了如何通过继承在python中子类化请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想专门化/子类化请求包以添加一些具有自定义功能的方法.

I would like to specialize / subclass the requests package to add some method with custom functionality.

我尝试这样做:

# concrete_requests.py
import requests

class concreteRequests(requests):
    def __init__(self):
        super(concreteRequests, self).__init__() 
        self.session()

    def login(self):
        payload = {'user': 'foo', 'pass': 'bar'}
        self.get('loginUrl', headers=header, data=payload)
        # more login stuff...

# my_class.py
class MyClass:
    def __init__():
        self.requests = concreteRequests()
        self.requests.login()

这样我仍然可以从 self.requests 成员 + 我的具体实现中受益.所以我可以这样做:self.requests.get(...)print(self.requests.post(...).status_code) 等等.

This way I could still benefit from self.requests members + my concrete implementation. So I could do: self.requests.get(...) or print(self.requests.post(...).status_code) and so on.

我猜这一行 super(concreteRequests, self).__init__() 可能愚蠢地无用,因为 requests 里面没有任何类声明,只是导入...

I guess that this line super(concreteRequests, self).__init__() can be stupidly useless since requests doesn't have any class declaration inside just imports...

那么,requests 包可以通过继承进行子类化/特化吗?

So, the requests package can be subclassed/specialized through inheritance ?

推荐答案

requests 是一个 python 模块而不是一个类.您只能对类进行子类化.

requests is a python module not a class. You can only subclass classes.

所以基本上你应该在你自己的内部利用它的方法/函数自定义类.

So basically you should just leverage its methods/functions inside your own custom class.

import requests

class MyRequests:
    def __init__(self, username, passwd):
        self.username = username
        self.passwd = passwd

    def get(self, *args, **kwargs):
        # do your thing
        resp = requests.get(...)
        # do more processing

我上面写的只是让你前进的一个例子.

What I wrote above is just an example to get you going.

这篇关于如何通过继承在python中子类化请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆