2 回答

TA貢獻1804條經驗 獲得超2個贊
你可以這樣做(你還需要正確使用請求和 url 作為字符串):
class Request_class(object):
'''
Class with all the requests
'''
def __init__(self, linkedin_url):
'''
Constructor
'''
#You can pass variables to create some class properties
#for example, if linkedin url is always the same
self.linkedin = linkedin_url
def facebook(self, url):
facebook = request_url(url)
facebook.apply(...)
...
def instagram(self, url):
instagram = request_url(url)
instagram.apply(...)
...
def linkedin(self):
#you don't need to pass the linkedin url; it's already a class property
linkedin = request_url(self.url)
linkedin.apply(...)
...
#Then you can create an instance of the class:
my_requests = Request_class('www.linkedin.com')
#And you can call its methods:
my_requests.facebook('www.facebook.com')
my_requests.instagram('www.instagram.com')
#For this last the class already knows the url
my_requests.linkedin()

TA貢獻1934條經驗 獲得超2個贊
首先創建 RequestClass 并給它一個 url 的屬性。然后您可以為每個站點使用不同的 url 創建對象。some_function() 可以是類方法:
class RequestClass:
def __init__(self, url):
self.url = url
def make_request(self):
request(self.url)
def some_function(self):
apply(...)
要創建一個對象:
fb = RequestClass("www.facebook.com")
ig = RequestClass("www.instagram.com")
li = RequestClass("www.linkedin.com")
fb.make_request()
ig.make_request()
li.make_request()
如果你想訪問請求中的數據,你可以在你的請求方法中將它保存為 self.data 假設你向站點發出請求的方式返回數據:
class RequestClass:
def __init__(self, url):
self.url = url
self.data
def make_request(self):
self.data = request(self.url)
要訪問數據,例如,來自 Facebook 的請求:
fb.data #returns the data from the request to facebook
process_data(fb.data) #easily use that data in a diff function
如果您在類中創建其他方法或屬性,則可以輕松地為每個站點訪問它們,例如,如果您想要打印請求中的數據:
fb.print_request_data()
ig.print_request_data()
li.print_request_data()
添加回答
舉報