在 Python 中将请求片段重组为 class OOP

Restructure request snippet into class OOP in Python

我测试了这段代码并得到了预期的结果:

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)

现在,我设法将其转换为 class,如下所示:

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)

不幸的是,结果是: 刚学了几天Python和OOP。请指导我通过这个例子了解更多。谢谢!

类 是创建 objects 的蓝图,所以首先你需要创建一个 getvps 的实例 class.

my_vps = getvps()

然后就可以在这个object上调用response方法了,记得调用方法的最后要加上() 所以你的代码的最后一行应该是这样的:

print(my_vps.getvps())

顺便说一下,classes 的命名习惯是用大写字母:

class Getvps

此外,如果您的 class 不是从 parent class 继承的,则无需在 class 名称后添加 ()。 最后,最好将 url 和 headers 定义为 object 属性而不是 class 变量