Pregunta

I suppose this is a bit of a beginner's question, but I'm wondering about the more pythonic approach to use when you're presented with a situation where you're using class methods from a class defined in a module, as well as methods defined within the module itself. I'll use numpy as an example.

import numpy as np

foo = np.matrix([[3, 4], [9, 12]])

# Get norm (without using linalg)
norm = np.sqrt(foo.dot(foo.T)).diagonal()

I can use a mixed case, like this, where I'm calling methods of foo and methods defined in numpy, or I can write the code as below:

norm = np.diagonal(np.sqrt(np.dot(foo, foo.T)))

I would prefer using foo.bar.baz.shoop.doop syntax, myself, but in this case I can't, as sqrt isn't a method of foo. So, what would be the more pythonic way to write a line like this?

Incidentally, as a side-question, are class methods usually more optimized, compared to methods defined in a module? I don't understand too well what's going on under the hood, but I assumed (again using numpy as an example) that numpy has an np.dot method that is written for the general case where arg can be an array or a matrix, while np.matrix.dot is reimplemented and optimized only for matrix operations. Please correct me if I'm wrong in this.

¿Fue útil?

Solución

The questions you're asking don't really have an answer, because the case you're asking about simply doesn't exist.

Typically, in Python, you do not have the same function available as a method and as a global function.

NumPy is a special case, because some, but not all, top-level functions are also available as methods on the appropriate object. Even then, they often don't have the same semantics, so the answer isn't a question of style, but of which one is the right function.

For example, in your case, the only one you have a choice on is diagonal. And the two options give different results.

>>> m = matrix([[1,2,3], [4,5,6], [7,8,9]]
>>> np.diagonal(m)
array([1, 5, 9])
>>> m.diagonal()
matrix([[1, 5, 9]])

The module function takes a 2D array of shape (N, N) and returns a 1D array of shape (N,). The method takes a 2D matrix of shape (N, N) and returns a 2D matrix of shape (1, N).

It's possible that the matrix method will be faster. But that's not as important as the fact that if one of them is correct, the other one is wrong. It's like asking whether + or * is a faster way to multiply two numbers. Whether + is faster than * or not, it's not a faster way to multiply, because it doesn't multiply.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top