How do I chain methods?

Chris Rebert clp2 at
Mon Oct 25 01:02:01 CEST 2010

On Sun, Oct 24, 2010 at 3:47 PM, chad <cdalten at> 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]$ ./
> Chad
> Traceback (most recent call last):
>  File "./", 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()

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

*Notwithstanding magic SQL query builders and the like

More information about the Python-list mailing list