How do I chain methods?

James Mills prologic at shortcircuit.net.au
Sun Oct 24 19:08:28 EDT 2010


On Mon, Oct 25, 2010 at 8:47 AM, chad <cdalten at gmail.com> wrote:
> 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]$

What you want is this:

>>> class Foo(object):
...     def first(self):
...             print "Chad "
...             return self
...     def last(self):
...             print "A "
...             return self
...
>>> x = Foo()
>>> y = x.first()
Chad
>>> y.last()
A
<__main__.Foo object at 0x1011d7ad0>
>>>

NB: You must return "self" in this case so you can do chained calls.

cheers
James

-- 
-- James Mills
--
-- "Problems are solved by method"



More information about the Python-list mailing list