Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #43304
| References | <CA923438-A718-46D4-9901-5043EACD7A22@york.ac.uk> |
|---|---|
| From | Ian Kelly <ian.g.kelly@gmail.com> |
| Date | 2013-04-10 17:40 -0600 |
| Subject | Re: Functional vs. Object oriented API |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.432.1365637782.3114.python-list@python.org> (permalink) |
On Wed, Apr 10, 2013 at 5:16 PM, Max Bucknell <mpwb500@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.
Back to comp.lang.python | Previous | Next | Find similar | Unroll thread
Re: Functional vs. Object oriented API Ian Kelly <ian.g.kelly@gmail.com> - 2013-04-10 17:40 -0600
csiph-web