1
我使用描述符來強制使用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)