On Sun, Oct 24, 2010 at 3:47 PM, chad <cdal...@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... > > [cdal...@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' > [cdal...@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 -- http://mail.python.org/mailman/listinfo/python-list