Home > Software engineering >  Restructure request snippet into class OOP in Python
Restructure request snippet into class OOP in Python

Time:10-23

I've tested this snippet and get the result as expected:

import requests
import json
url = 'https://example.com/getlistitem'
headers= {
        'User-Agent': 'Mozilla/5.0', 
        'Referer': 'http://banggia.tvs.vn/',
        'content-type': 'text/json',
        'Content-Type': 'application/json;charset=utf-8'
    }

res=requests.get(url, headers = headers, timeout= 30).json()
print(res)

Now, I manage to convert it into class as this:

class getvps():
    url = 'https://example.com/getlistitem'
    headers= {
        'User-Agent': 'Mozilla/5.0', 
        'Referer': 'http://banggia.tvs.vn/',
        'content-type': 'text/json',
        'Content-Type': 'application/json;charset=utf-8'
    }
    
    def response(self):
        return requests.get(self.url, headers = self.headers, timeout= 30).json()
    

if __name__ == '__main__':
    
    print(getvps.response)

Unforturnately, the result was: <function getvps.response at 0x034527C8> I have just learned Python and OOP for a few days. Please guide me to learn more via this example. Thanks!

CodePudding user response:

Classes are blue prints to create objects, so first of all you need to create an instance of getvps class.

my_vps = getvps()

Then you can call response method on this object, remember for calling a method you should put () at the end of it so the last line of your code should looks like this:

print(my_vps.getvps())

By the way it is convention to name classes with capital letters:

class Getvps

Also there is no need to put () after class name, if your class doesn't inherit from a parent class. Finally it's better to define url and headers as object attribute rather than class variables

  • Related