我使用描述符来强制使用 numpy 数组。这很好用,但现在我想知道一个类的属性是否是实例Spectrum
。我的想法是检查obj.__dict__
并使用isinstance(obj, Spectrum)
,但是Spectrum.__get__
会返回数组,因此isinstance(obj, Spectrum)
会失败。有什么办法可以解决这个问题?
class Spectrum(object):
"""Class capable of containing spectral values."""
def __init__(self, name, dtype='float64'):
self.name = name
def __get__(self, instance, cls):
if instance is None:
return self
else:
print instance.__dict__
return instance.__dict__[self.name]
def __set__(self, instance, value):
if not isinstance(value, np.ndarray):
raise TypeError('Expected an ndarray')
instance.__dict__[self.name] = value
def __delete__(self, instance):
del instance.__dict__[self.name]
class Material(object):
loss_factor = Spectrum(name='loss_factor', dtype='Float64')
def __init__(self):
self.loss_factor = np.array([1, 2, 3])
def main():
obj = Material()
print isinstance(obj.loss_factor, Spectrum)