Functional vs. Object oriented API
Ian Kelly
ian.g.kelly at gmail.com
Wed Apr 10 19:40:48 EDT 2013
On Wed, Apr 10, 2013 at 5:16 PM, Max Bucknell <mpwb500 at york.ac.uk> wrote:
> I also have a function to generate the dot product of these two vectors. In Java, such a function would be put as a method on the class and I would do something like:
>
> >>> a.dot_product(b)
> 7
>
> and that would be the end of it. But in Python, I can also have:
>
> >>> dot_product(a, b)
> 7
>
> Which of these two are preferred in Python? And are there any general guidelines for choosing between the two styles, or is it largely a matter of personal preference?
The advantage to the latter is that it potentially allows you to
implement dot products for other types using the same function. Using
the method, a must be a Vector instance, but using the function it
remains unrestricted.
This is useful because functions are first-class objects in Python.
Suppose that you find yourself wanting to pass that dot_product
operation to some other function, e.g. map(). Using the function
version you just pass in dot_product -- map(dot_product, seq1, seq2)
-- and the mapped sequences can then contain any types that
dot_product has been implemented to handle. Using the method version,
you would have to pass in the unbound Vector.dot_product method --
map(Vector.dot_product, seq1, seq2), and then the method will only
accept Vector instances in seq1.
More information about the Python-list
mailing list