How do I chain methods?
clp2 at rebertia.com
Mon Oct 25 01:02:01 CEST 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...
> class foo:
> def first(self):
> print "Chad "
> def last(self):
> print "A "
> x = foo()
> y = x.first()
> But when I ran it, I got the following...
> [cdalten at localhost oakland]$ ./chain.py
> Traceback (most recent call last):
> File "./chain.py", line 12, in ?
> 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