Chain together methods in Python as in Ruby -


in ruby, 1 can chain methods so:

a = [2,3,1] b = a.sort.reverse 

which sets value of variable b [3,2,1] while leaving a same.

i'd perform similar operations in python. far, shortest way have found is:

import copy = [2,3,1] b = copy.copy(a) b.sort() b.reverse() 

that is, 5 lines of code instead of 2. there no simpler way?

clarification: original answer found below. commented, question on chaining in general, not in specific case. clarification on can found @ end of answer.


you can write down pretty directly.

a = [2,3,1] b = sorted(a, reverse=true) 

even if want use methods, can rather straightforward well:

a = [2,3,1] b = a.copy()  # a[:] in python2 b.sort(reverse=true) 

python tends rather picky implicit cloning. copying references cheap, copying objects expensive. since many python types mutable, 1 can introduce subtle bugs when things cloned (or not) accident. thus, interfaces need explicitly clone things.


chaining methods in python possible. however, chains apply objects returned previous method (or function) calls.

basically, chaining method calls chaining functions.

foo = they.method.method.method() foo = my_func(your_func(their_func())) 

let's consider [2,3,1].sort().reverse(). equivalent following:

a = [2,3,1] b = a.sort() c = b.reverse() 

since s.sort() returns none, third line call none.reverse() - not defined none.

immutable types behave better here. example, strings cannot modified inplace - methods return new strings. thus,

s = "ab:cd".upper().center(20).partition(':') print(s) 

gives (' ab', ':', 'cd ').


Comments

Popular posts from this blog

sequelize.js - Sequelize group by with association includes id -

android - Robolectric "INTERNET permission is required" -

java - Android raising EPERM (Operation not permitted) when attempting to send UDP packet after network connection -