How do I chain methods?

Chris Rebert clp2 at rebertia.com
Sun Oct 24 19:02:01 EDT 2010


On Sun, Oct 24, 2010 at 3:47 PM, chad <cdalten at gmail.com> wrote:
> How do I chain methods?
> I tried the following...
>
> #!/usr/bin/python
>
> class foo:
>    def first(self):
>        print "Chad "
>
>    def last(self):
>        print "A "
>
> x = foo()
> y = x.first()
> y.last()
>
> But when I ran it, I got the following...
>
> [cdalten at localhost oakland]$ ./chain.py
> Chad
> Traceback (most recent call last):
>  File "./chain.py", line 12, in ?
>    y.last()
> AttributeError: 'NoneType' object has no attribute 'last'
> [cdalten at localhost oakland]$

Functions/methods without "return" statements, such as your last() and
first(), implicitly return None, Python's equivalent of null. Python
has no special support for method chaining; having your methods
`return self` achieves the same effect however.

Method chaining is usually* not idiomatic in Python. Most people would
instead just write:
x = foo()
x.first()
x.last()

If you insist on method chaining, adding the aforementioned `return`
statements would let you write:
x = foo()
x.first().last()

Cheers,
Chris
--
*Notwithstanding magic SQL query builders and the like
http://blog.rebertia.com



More information about the Python-list mailing list