method chaining in python

前端 未结 4 553
故里飘歌
故里飘歌 2020-12-07 17:56

(not to be confused with itertools.chain)

I was reading the following: http://en.wikipedia.org/wiki/Method_chaining

My question is: what is the best

4条回答
  •  旧时难觅i
    2020-12-07 18:26

    There isn't going to be any general way of allowing any method of any object to be chained, since you can't know what sort of value that method returns and why without knowing how that particular method works. Methods might return None for any reason; it doesn't always mean the method has modified the object. Likewise, methods that do return a value still might not return a value that can be chained. There's no way to chain a method like list.index: fakeList.index(1).sort() can't have much hope of working, because the whole point of index is it returns a number, and that number means something, and can't be ignored just to chain on the original object.

    If you're just fiddling around with Python's builtin types to chain certain specific methods (like sort and remove), you're better off just wrapping those particular methods explicitly (by overriding them in your wrapper class), instead of trying to do a general mechanism with __getattr__.

提交回复
热议问题