Home > OS >  How can I inherit from classes I didn't make like requests in python
How can I inherit from classes I didn't make like requests in python

Time:04-01

I am building an object-oriented app that utilizes the requests lib for sending and receiving data from an API, but I can't manage to find out a way to inherit from the requests module. not just for requests but for Tkinter also.

the general problem is that I can't really inherit from classes I didn't make personally like third party lib

All I want to do is just simply say "self.get" or "self.post" .

here is a code example of what I want to do: -

import requests 
class Create(requests):
      def __init__(self):
          super().__init__()
      def create(self):
          self.post(url,headers,data)

I tried several methods even including modifying the original code of the lib to make classes I can inherit from but it didn't work either

CodePudding user response:

There's nothing special about inheriting from 3rd-party classes, inheritance works just like with your own classes:

>>> import requests
>>> requests.Request
<class 'requests.models.Request'>
>>> class MyRequest(requests.Request):
...  def say_hello(self):
...   print("Hello!")
... 
>>> MyRequest()
<Request [None]>
>>> MyRequest().say_hello()
Hello!
>>> 

CodePudding user response:

With requests, you want to derive from requests.Session. (The requests.post, etc. helpers just build an one-shot session and call the method by the same name.)

Like so:

import requests

class MySession(requests.Session):
     base_url = "https://example.com"

     def create(self, data):
         return self.post(f"{self.base_url}/create", json=data)

sess = MySession()
sess.create("hello")  # does a POST to https://example.com/create
  • Related