如何应用Python类方法装饰器GETTER和SETTER?

问题描述 投票:0回答:1

我目前正在学习Python类方法中的GETTER和SETTER属性,但是我不太明白如何应用它,

以下是我的代码,请告诉我:

  1. 如果我正确使用了“类变量”和“实例变量” - 有更好的方法吗?
  2. 如何转换 set_destination_id 和 set_chat_message 以使用 GETTER 和 SETTER 装饰器?
import datetime
import json

import requests


class BotLine:
    secret_token = ("secret_token_here")
    endpoint_url = "https://api.line.me/v2/bot/message/push"
    destination_id_test = "test_group_id"
    destination_id_real = "real_group_id"
    auth_bearer = f"Bearer {secret_token}"
    headers = {"Content-Type": "application/json", "Authorization": auth_bearer}

    def __init__(self, test_mode="Y"):
        self.chat = None
        self.data = None
        self.destination_id = self.set_destination_id(test_mode)

    def set_destination_id(self, test_mode=None) -> str:
        return self.destination_id_real if test_mode == 'N' else self.destination_id_test

    def set_chat_message(self, chat=None) -> object:
        self.data = {"to": self.destination_id,
                     "messages": [
                         {"type": "text",
                          "text": f"$ {chat} $",
                          "emojis": [
                              {"index": 0,
                               "productId": "5ac2213e040ab15980c9b447",
                               "emojiId": "001"}
                          ]
                          },
                         {"type": "sticker",
                          "packageId": "6136",
                          "stickerId": "10551377"
                          }
                     ]
                     }
        return self.data

    def send_to_chat(self, chat=None) -> json:
        return json.loads(requests.post(self.endpoint_url, data=json.dumps(self.set_chat_message(chat)), headers=self.headers, verify=False).text)


if __name__ == "__main__":
    chat_message = f"\N{Robot Face}: Testing - {datetime.datetime.now().strftime('%Y%m%d%H%M%S')}"
    bot = BotLine(test_mode="Y")
    response = bot.send_to_chat(chat=chat_message)
    print(f"{json.dumps(response, indent=2)}")

谢谢你,

python class get set decorator
1个回答
0
投票

1.如果我正确使用了“类变量”和“实例变量”——还有更好的方法吗?

我认为 auth_bearer 和 headers 有一个像“Bearer”或{“Content-Type”:“application/json”,“Authorization”:auth_bearer}这样的泡沫,并且这不会经常改变。 因此,将 auth_bearer_foam 和 headers_foam 作为类变量(包括端点_url)。现在将其他变量作为即时变量,因为这会经常更改。

class BotLine:
    endpoint_url = "https://api.line.me/v2/bot/message/push"
    auth_bearer_foam = "Bearer "
    headers_foam = {"Content-Type": "application/json", "Authorization": "default"}

    def __init__(self, secret_token,destination_id_real,destination_id_test,chat,test_mode="Y"):
        self.destination_id_real=destination_id_real
        self.destination_id_test=destination_id_test
        self.__secret_token=secret_token #it should be private varible for security
        self.__chat=chat
        self.test_mode=test_mode

2.如何将set_destination_id和set_chat_message转换为使用GETTER和SETTER装饰器?

使用属性装饰器,它以与使用常规字段相同的方式创建 getter 和 setter。 例如

class Public:
    def __init__(self, name):
        self.__name = name

    @property
    def name(self):
        return self.__name

    @name.setter
    def name(self, new_name):
        #add some validation for new_name
        self.__name = new_name

public1 = Public("steve")
print(public1.name)
public1.name = "elice"
print(public1.name)

这是我的代码,带有属性装饰器和一些更改

class BotLine:
    endpoint_url = "https://api.line.me/v2/bot/message/push"
    auth_bearer_foam = "Bearer "
    headers_foam = {"Content-Type": "application/json", "Authorization": "default"}

    def __init__(self, secret_token,destination_id_real,destination_id_test,chat,test_mode="Y"):
        self.destination_id_real=destination_id_real
        self.destination_id_test=destination_id_test
        self.__secret_token=secret_token
        self.__chat=chat
        self.test_mode=test_mode

    @property
    def secret_token(self):
        return self.__secret_token
    
    @secret_token.setter
    def secret_token(self,new_secret_token):
        #add some validdation about new_secret_token
        self.__secret_token=new_secret_token
    
    
    @property
    def chat(self):
        return self.__chat
    
    @chat.setter
    def chat(self,new_chat:str):
        #add some validdation about new_chat
        self.__chat=new_chat
    
    #you can get a headers with current secret_token
    @property
    def headers(self)->str:
        headers={key: value[:] for key, value in BotLine.headers_foam.items()}
        headers["Authorization"]=BotLine.auth_bearer_foam+self.secret_token
        return headers

    #you can get a destination_id with current test_mode
    @property
    def destination_id(self) -> str:
        return self.destination_id_real if self.test_mode == 'N' else self.destination_id_test
    
    
    @property
    def chat_message(self)->object:
        return {
                "to": self.destination_id,
                "messages": [
                    {
                        "type": "text",
                        "text": f"$ {self.chat} $",
                        "emojis": [
                            {"index": 0,
                            "productId": "5ac2213e040ab15980c9b447",
                            "emojiId": "001"}
                        ]
                    },
                    {
                        "type": "sticker",
                          "packageId": "6136",
                          "stickerId": "10551377"
                    }
                ]
            }

    def send_to_chat(self) -> json:
        return json.loads(requests.post(self.endpoint_url, data=json.dumps(self.chat_message), headers=self.headers, verify=False).text)


if __name__ == "__main__":
    chat = f"\N{Robot Face}: Testing - {datetime.datetime.now().strftime('%Y%m%d%H%M%S')}"
    bot = BotLine(test_mode="Y",secret_token ="secret_token_here",destination_id_test="test_group_id",destination_id_real="real_group_id",chat=chat)
    response = bot.send_to_chat()
    print(f"{json.dumps(response, indent=2)}")
© www.soinside.com 2019 - 2024. All rights reserved.