Python class methods, when to return self?

前端 未结 2 1904
伪装坚强ぢ
伪装坚强ぢ 2021-01-03 16:27

I\'m confused as to when to return self inside a class and when to return a value which may or may not possibly be used to check the method ran correctly.

de         


        
2条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-03 16:45

    Generally, objects in python are mutable. You therefore do not return self, as the modifications you make in a method are reflected in the object itself.

    To use your example:

    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
    

提交回复
热议问题