How do I alias member functions in Python?
No problemo! You can alias a method, but you have to know how to use it:
>>> r=str.replace
>>> a='hello'
>>> r(r(r(r(a,'h','j'),'e','i'),'l','m'),'o','y')
'jimmy'
The key is that you have to pass self
explicitly, because the alias is a kind of function that takes an extra argument that takes self
:
>>> type(r)
<type 'method_descriptor'>
Define your own class, with a shorter method name.
For example, if you're using the method replace()
belonging to the String
class, you could make your own class S
have a method called q
which does the same thing.
Here is one implementation:
class m(str):
def q(a,b,c):return m(a.replace(b,c))
Here is a much better implementation:
class m(str):q=lambda a,b,c:m(a.replace(b,c))
Use it like so:
s="Hello"
s=m(s).q('H','J').q('e','i').q('l','m').q('o','y')
This is a few characters shorter anyway
j=iter('HJeilmoy')
for i in j:s=s.replace(i,next(j))
even shorter for a small number of replacements is
for i in['HJ','ei','lm','oy']:s=s.replace(*i)
of course this just covers one particular case. However code golf is all about finding those special cases that can save you bytes.
It's possible to write a wrapper function that handles the general case, but the code will be too large to have a place in most code golf challenges.
You instead need to think "I can do this transformation efficiently (strokewise) with str.replace. Can I shift the internal representation of my solution to take advantage of that? (without wasting so many strokes to negate the advantage)"