簡體   English   中英

使用該子類的變量從子類調用父方法

[英]Calling a parent method from a child class with a variable of that child

開始研究我的 Python Keitaro Admin API 庫。 我需要請求幾個目標。 喜歡優惠、活動、流或聯盟網絡。 他們有類似的請求網址,例如:

  1. https://example.com/v1/admin_api/offers如果我需要與優惠互動
  2. https://example.com/v1/admin_api/campaigns如果我需要與活動等互動。

我想像這樣在 python 代碼中與 API 交互:使用類變量 url 和 api_key 創建類似對象 Keitaro。 還有像get和post這樣的keitaro方法。 然后將變量“目標”添加到子類中,這樣我就可以使用“目標”變量的報價或活動調用 Keitaro get/post 方法。

所需的代碼模式:

from keitaropy import Keitaro

app = Keitaro('https://example.com/', 'api_key')
offer_of_app = app.offer.get(123) # get by id
offers_of_app = app.offer.get() # get all

app2 = Keitaro('https://otherurl.com/', 'other_api_key')
offer_of_app2 = app2.offer.get(11)
offers_of_app2 = app2.offer.get()

為什么我認為這個代碼片段比下面的代碼片段更好:我不需要導入像 Offer、Streams、Campaigns 這樣的子類。 我可以只導入 Keitaro 類並通過調用該類作為方法 offer/campaign/stream 來使用 childs 的目標變量,如上所述。

我取得了什么:

from keitaropy import Offer

offer_app = Offer('https://example.com/', 'api_key')
offer = offer.get(123)
offers = offer.get()

keitaropy代碼:

import requests
import json


def add_target_path(base_url, target, separator = '/'):
if base_url.endswith(separator):
    url = base_url + target
else:
    url = base_url + separator + target
return url

    
class Keitaro:
    def __init__(self, base_url, api_key, target):
        self.headers = { 'Api-Key': api_key }
        self.base_url = base_url
        self.target = target


    def get(self, target_id = None):
        url = add_target_path(self.base_url, self.target)
        if target_id:
            # get by id
            url = add_target_path(url, target_id)
        # if no id get all
        response = requests.get(url, headers=self.headers)
        return response.json()


    def post(self, data):
        pass


class Offer(Keitaro):
    def __init__(self, base_url, api_key):
        self.target = 'offers'
        super().__init__(base_url, api_key, self.target)


class Campaign(Keitaro):
    def __init__(self, base_url, api_key):
        self.target = 'campaigns'
        super().__init__(base_url, api_key, self.target)


class Stream(Keitaro):
    def __init__(self, base_url, api_key):
        self.target = 'streams'
        super().__init__(base_url, api_key, self.target)


class AffNetwork(Keitaro):
    def __init__(self, base_url, api_key):
        self.target = 'affiliate_networks'
        super().__init__(base_url, api_key, self.target)

我不喜歡在父類中存儲子變量 'target' 只是為了調用父方法 get 的想法,但沒有任何想法可以做得更好。 如果您有一些想法,請與我分享

此外,孩子的 Campaign、Offer 等也可以擁有自己的方法,這些方法不是父類中固有的。

父類具有直接使用的target類的屬性沒有任何問題。 子類設置值也沒有錯:

class Offer(Keitaro):
    def __init__(self, base_url, api_key):
        super().__init__(base_url, api_key, 'offers')

您剛剛獲得了一個好處,即OfferCampaign等類減少了實例化類所需的參數數量。

您可以避免通過構造函數傳遞 'target' 變量,而是在將 target 作為參數傳遞時直接從 child 中的首選方法調用父 get 方法。

問題的答案比我預期的要復雜。 你可以在我的GitHub 存儲庫中查看它的示例

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM