Learning Python now coming from Perl
Roy Smith
roy at panix.com
Mon Dec 8 10:28:36 EST 2008
In article <slrngjps0o.51b.nick at irishsea.home.craig-wood.com>,
Nick Craig-Wood <nick at craig-wood.com> wrote:
> My favourite mistake when I made the transition was calling methods
> without parentheses. In perl it is common to call methods without
> parentheses - in python this does absolutely nothing! pychecker does
> warn about it though.
>
> perl -> $object->method
> python -> object.method()
On the other hand, leaving out the parens returns the function itself,
which you can then call later. I've often used this to create data-driven
logic.
For example, I'm currently working on some code that marshals objects of
various types to a wire protocol. I've got something like:
encoders = {
SM_INT: write_int,
SM_SHORT: write_short,
SM_FLOAT: write_float,
# and so on
}
class AnyVal:
def __init__(self, type, value):
self.type = type
self.value = value
def write_anyval(any):
encoders[any.type](any.value)
The fact that functions are objects which can be assigned and stored in
containers makes this easy to do.
More information about the Python-list
mailing list