About
Ross Lawleys tumblelog mainly on software and agile methods.
Accounts
Newer posts are loading.
You are at the newest post.
Click here to check if anything new just came in.
Click here to check if anything new just came in.
June 25 2009
“— Understanding PythonI've seen a number of people on the Ruby newsgroup who really misunderstand the explicit self argument in Python methods. While Python's style is certainly not the only approach, it *does* allow a genericity that is less easy in most all other languages. The explicit self is distinctly a Python *feature*, not a flaw. Some of the other criticisms are a bit misguided too. For example, the widespread upset at significant indentation vanishes from 99% of Python users after a few days/weeks of actual usage. Almost all of those folks wind up thinking of the indentation as a feature. But that's largely a matter of taste (with which there is no arguing :-)). The self thing, however, is worth an explicit explanation. The point of the explicit self is that it allows detaching a method from an instance, and passing a different instance to the same method. In the simple case this is sorta pointless: >>> class Klass: ... def __init__(self, data=None): ... self.data = data ... def say(self): ... print self.data ... >>> this = Klass('this') >>> that = Klass('that') >>> just_say = Klass.say >>> this.say() this >>> that.say() that >>> just_say(this) this >>> just_say(that) that Whether one uses the method or the function-with-argument amounts to the same thing where one names instances. But consider nameless instances: >>> klasses = [Klass('this'), Klass('that'), Klass('other')] One can use an index into a data structure to call the detached class method like: >>> just_say(klasses[1]) that Of course, that's still not such a big thing, since one can also write: >>> klasses[1].say() that Where it becomes really interesting is in genuinely nameless functional-programming style constructs like: >>> map(just_say, klasses) this that other [None, None, None] AFAIK (which is only a little Ruby), one would do this in Ruby by iterating over a code block... but the code block would still use a temporary name to refer to the object whose method is called. There's nothing wrong with this... but it becomes slightly less elegant once you get into more complicated function/class factories and generic FP programming.”
