Python类方法,何时返回self?

时间:2013-07-03 23:58:53

标签: python oop

我很困惑何时在类中返回self以及何时返回一个值,该值可能会或可能不会用于检查方法是否正确运行。

def api_request(self, data):
    #api web request code
    return response.text
def connect(self):
    #login to api, set some vars defined in __init__
    return self
def send_message(self, message):
    #send msg code
    return self

以上是一些例子。 api_request我知道文本响应是必须的。但是使用send_message我应该返回什么?

然后转换为dict以检查密钥是否存在,否则引发错误)。

它应该返回True,响应 - > dict,还是self?

提前致谢

2 个答案:

答案 0 :(得分:2)

通常,python中的对象是可变的。因此,您不会返回self,因为您在方法中所做的修改会反映在对象本身中。

使用您的示例:

api = API() # initialise the API
if api.connect(): # perhaps return a bool, indicating that the connection succeeded
    api.send_message() # you now know that this API instance is connected, and can send messages

答案 1 :(得分:2)

由于错误往往是作为异常传递的,因此成功/失败返回值很少有用,很多对象修饰符函数最终都没有返回值 - 或者更确切地说,返回None,因为你什么都不能回归。 (考虑一些Python的内置对象,如list,其中appendextend返回Nonedict,其中dict.update返回None。)

尽管如此,返回self对于链接方法调用很方便,即使某些Pythonist不喜欢它。例如,请参阅Should internal class methods returnvalues or just modify instance variables in python?中的kindall答案。


编辑以根据评论添加一些示例:

你应该“返回”或引发异常,在这种情况下,“什么异常” - 取决于问题。您希望send_message()等待响应,验证响应并验证它是否正常?如果是这样,如果没有响应,验证失败或响应有效但是说“消息被拒绝”,您是否希望它引发错误?如果是这样,您是否希望每次失败都有不同的错误等?一个合理的(对于某些合理的值)方法是捕获具有“基础”异常的所有失败,并使每个“类型”的失败成为其衍生物:

class ZorgError(Exception):      # catch-all "can't talk via the Zorg-brand XML API"
    pass

class ZorgRemoteDown(ZorgError): # connect or send failed, or no response/timeout
    pass

class ZorgNuts(ZorgError):       # remote response incomprehensible
    pass

class ZorgDenied(ZorgError):     # remote says "permission denied"
    pass

# add more if needed

现在你的一些函数可能看起来像这样(注意,这些都没有经过测试):

def connect(self):
    """connect to server, log in"""
    ... # do some prep work
    addr = self._addr
    try:
        self._sock.connect(addr)
    except socket.error as err:
        if err.errno == errno.ECONNREFUSED: # server is down
            raise ZorgRemoteDown(addr)      # translate that to our Zorg error
        # add more special translation here if needed
        raise                               # some other problem, propagate it
    ... # do other stuff now that we're connected, including trying to log in
    response = self._get_response()
    if response == 'login denied'   # or whatever that looks like
        raise ZorgDenied()          # maybe say what exactly was denied, maybe not
    # all went well, return None by not returning anything

def send_message(self, msg):
    """encode the message in the way the remote likes, send it, and wait for
    a response from the remote."""
    response = self._send_and_wait(self._encode(msg))
    if response == 'ok':
        return
    if response == 'permission denied':
        raise ZorgDenied()
    # don't understand what we got back, so say the remote is crazy
    raise ZorgNuts(response)

然后你需要一些像这样的“内部”功能:

def _send_and_wait(self, raw_xml):
    """send raw XML to server"""
    try:
        self._sock.sendall(raw_xml)
    except socket.error as err:
        if err.errno in (errno.EHOSTDOWN, errno.ENETDOWN) # add more if needed
            raise ZorgRemoteDown(self._addr)
        raise
    return self._get_response()

def _get_response(self):
    """wait for a response, which is supposedly XML-encoded"""
    ... some code here ...
    if we_got_a_timeout_while_waiting:
       raise ZorgRemoteDown(self._addr)
    try:
        return some_xml_decoding_stuff(raw_xml)
    except SomeXMLDecodeError:
        raise ZorgNuts(raw_xml) # or something else suitable for debug

您可以根本不选择翻译socket.error,也不要拥有自己的所有错误;也许您可以将错误压缩到ValueErrorKeyError等等。例如。

这些选择就是编程的全部内容!