【问题标题】:Python: How to use method with decorator properlyPython:如何正确使用带有装饰器的方法
【发布时间】:2016-05-10 14:19:01
【问题描述】:

我有一个Message 类,我想设置它的有效负载。但是,我无法弄清楚如何使用正确的方法来做到这一点。这是Message 类在源代码中的样子(删除了不相关的部分):

class Message(object):
    def __init__(self):
        self._type = None
        self._mid = None
        self._token = None
        self._options = []
        self._payload = None
        self._destination = None
        self._source = None
        self._code = None
        self._acknowledged = None
        self._rejected = None
        self._timeouted = None
        self._cancelled = None
        self._duplicated = None
        self._timestamp = None
        self._version = 1

    @property
    def payload(self):
        """
        Return the payload.

        :return: the payload
        """
        return self._payload

    @payload.setter
    def payload(self, value):
        """
        Sets the payload of the message and eventually the Content-Type

        :param value: the payload
        """
        if isinstance(value, tuple):
            content_type, payload = value
            self.content_type = content_type
            self._payload = payload
        else:
            self._payload = value

如果我尝试使用messageObject.payload("Hello World") 设置有效负载,则会收到错误:TypeError: 'NoneType' object is not callable

设置有效载荷的正确方法是什么?

【问题讨论】:

    标签: python decorator getter-setter python-decorators


    【解决方案1】:

    当你使用property decorator时,payload不再作为方法使用,它变成了属性,表示装饰器名称,用法如下:

    message_object.payload = "Hello World" # set the payload property
    message_object.payload # get the payload property
    

    【讨论】:

      猜你喜欢
      • 2014-06-08
      • 2020-09-05
      • 1970-01-01
      • 2014-10-17
      • 2019-11-17
      • 1970-01-01
      • 2011-12-15
      • 1970-01-01
      相关资源
      最近更新 更多