问题
Is there a more beautiful way than:
import numpy as np
from numpy import ma
def foo(x):
pkg = ma if isinstance(x, ma.MaskedArray) else np
return pkg.apply_along_axis(bar, -1, x)
I feel it not Pythonic, in terms of trying to make the most out of polymorphism.
EDIT
The above code snippet is just a demo to highlight the fact that np and ma have highly similar (designed on purpose) interface (e.g., apply_along_axis), but under different namespace.
回答1:
isinstance() is fine as it is here.
You could make it implicit if you'd like using a single-dispatch generic function:
from pkgutil import simplegeneric
import numpy as np
from numpy import ma
@simplegeneric
def pkg(obj):
return np # use numpy by default
@pkg.register(ma.MaskedArray)
def _(x):
return ma
def foo(x):
return pkg(x).apply_along_axis(bar, -1, x)
Here's another example of generic function in Python.
来源:https://stackoverflow.com/questions/20771788/best-practice-to-write-generic-numerical-functions-that-work-with-both-ndarray-a