23
0
In Python, one can save bytes by aliasing functions that are used repeatedly. For example:
r=range
a=r(100)
b=r(200)
c=r(300)
However, when the functions are member functions together, I don't know how to alias them in a way that allows chaining. For example:
s='Hello'
// Plain code
s=s.replace('H','J').replace('e','i').replace('l','m').replace('o','y')
// What I am trying to do
q=replace
s=s.q('H','J').q('e','i').q('l','m').q('o','y')
Obviously, what I am trying to do is not valid. And neither is this:
q=s.replace
s=q('H','J') // Replaces the 'H' in 'Hello'
s=q('e','i') // Replaces the 'e' in 'Hello'... and the J is gone.
s=q('l','m')
s=q('o','y')
Is there a another way to alias member functions and chained functions that saves characters?
Define your own class, with its method
q
meaning whatreplace
means in the class your using. – Ypnypn – 2014-05-08T21:07:49.720@Ypnypn I see. So you alias the class rather than the function. It seems obvious now that you said it. Do you want to post your answer? I'll even expand it with an example when I get around to it, but I don't get any rep for answering my own question. – Rainbolt – 2014-05-08T21:15:45.313
3I'm glad this hasn't been downvoted :) – TheDoctor – 2014-05-08T23:08:01.700
I have literally no idea why this kind of tips question has to CW, too. – Martin Ender – 2014-05-09T22:20:49.367
2
I've unwikied all the answers for now, but we haven't reached a strong enough consensus to call for unwiki-ing this and similar questions. See also: http://meta.codegolf.stackexchange.com/q/1555/3808
– Doorknob – 2014-05-10T14:34:45.8203Now that the aforementioned meta discussion is semi-official (or at least most of us agree), I've gone ahead and removed the wiki on this post. – Doorknob – 2014-05-13T21:58:04.860
1Your last version doesn't work.
q
is bound to the replace method of that specificstr
instance. Also, remember you can do single char replacements with"Hello".replace(*"HJ")
– gnibbler – 2014-05-14T01:40:18.473@gnibbler Wow, you're right. I guess I never actually tested the bad version. I'll modify the question. – Rainbolt – 2014-05-14T12:58:57.513