在我正在研究的特定项目中,检索通过** kwargs传递的关键字参数的顺序将非常有用。这是关于制作一种具有有意义尺寸的nd numpy数组(现在称为dimarray),对地球物理数据处理特别有用。
现在说我们有:
import numpy as np
from dimarray import Dimarray # the handy class I am programming
def make_data(nlat, nlon):
""" generate some example data
"""
values = np.random.randn(nlat, nlon)
lon = np.linspace(-180,180,nlon)
lat = np.linspace(-90,90,nlat)
return lon, lat, values
Run Code Online (Sandbox Code Playgroud)
什么有效:
>>> lon, lat, values = make_data(180,360)
>>> a = Dimarray(values, lat=lat, lon=lon)
>>> print a.lon[0], a.lat[0]
-180.0 -90.0
Run Code Online (Sandbox Code Playgroud)
什么不是:
>>> lon, lat, data = make_data(180,180) # square, no shape checking possible !
>>> a = Dimarray(values, lat=lat, …Run Code Online (Sandbox Code Playgroud) 在包含numpy数组作为属性的类中重载运算符时,我遇到了一个问题.根据操作数的顺序,结果类型将是我的类A(所需行为)或numpy数组.如何使它始终返回A的实例?
例:
import numpy as np
class A(object):
""" class overloading a numpy array for addition
"""
def __init__(self, values):
self.values = values
def __add__(self, x):
""" addition
"""
x = np.array(x) # make sure input is numpy compatible
return A(self.values + x)
def __radd__(self, x):
""" reversed-order (LHS <-> RHS) addition
"""
x = np.array(x) # make sure input is numpy compatible
return A(x + self.values)
def __array__(self):
""" so that numpy's array() returns values
"""
return self.values
def …Run Code Online (Sandbox Code Playgroud)