python - Pythonic use of class and module methods -


i suppose bit of beginner's question, i'm wondering more pythonic approach use when you're presented situation you're using class methods class defined in module, methods defined within module itself. i'll use numpy example.

import numpy np  foo = np.matrix([[3, 4], [9, 12]])  # norm (without using linalg) norm = np.sqrt(foo.dot(foo.t)).diagonal() 

i can use mixed case, this, i'm calling methods of foo , methods defined in numpy, or can write code below:

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

i prefer using foo.bar.baz.shoop.doop syntax, myself, in case can't, sqrt isn't method of foo. so, more pythonic way write line this?

incidentally, side-question, class methods more optimized, compared methods defined in module? don't understand what's going on under hood, assumed (again using numpy example) numpy has np.dot method written general case arg can array or matrix, while np.matrix.dot reimplemented , optimized matrix operations. please correct me if i'm wrong in this.

the questions you're asking don't have answer, because case you're asking doesn't exist.

typically, in python, not have same function available method , global function.

numpy special case, because some, not all, top-level functions available methods on appropriate object. then, don't have same semantics, answer isn't question of style, of 1 right function.

for example, in case, 1 have choice on diagonal. , 2 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 2d array of shape (n, n) , returns 1d array of shape (n,). method takes 2d matrix of shape (n, n) , returns 2d matrix of shape (1, n).

it's possible matrix method faster. that's not important fact if 1 of them correct, other 1 wrong. it's asking whether + or * faster way multiply 2 numbers. whether + faster * or not, it's not faster way multiply, because doesn't multiply.


Comments