Python:如何正确使用装饰器的方法

时间:2016-05-10 14:19:02

标签: python decorator getter-setter python-decorators

我有一个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

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

1 个答案:

答案 0 :(得分:1)

当您使用property decorator时,payload不再被用作方法,它将成为属性,表示装饰者名称并按如下方式使用:

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