我陷入以下困境。我正在尝试使用默认值初始化一些类属性,其中默认值是可变序列类型(列表和 numpy 数组)。因为我想在每次从类外部设置属性时进行一些错误检查,所以我正在使用@property 功能。
import numpy as np
from FDTimeBase import FDTimeBase
from FDString import FDString
class FDObjNetwork(FDTimeBase):
def __init__(self,i_mechObjs=[FDString(),FDString(101)],i_connPointMatrix=np.array([[0.5],[0.5]]),\
i_excPointMatrix=np.array([[0.5],[0.]])):
self._mechObjs = i_mechObjs
self._connPointMatrix = i_connPointMatrix
self._excPointMatrix = i_excPointMatrix
@property
def mechObjs(self):
"""the mechanically vibrating objects making up the network"""
return self._mechObjs
@property
def connPointMatrix(self):
"""
the connection point matrix of the network, where each row
denotes a separate element in the network and each column
denotes a separate connection
"""
return self._connPointMatrix
@property
def excPointMatrix(self):
"""
the excitation point matrix, where each row denotes a
separate element in the network and each column denotes a
separate excitation distribution
"""
return self._excPointMatrix
@mechObjs.setter
def mechObjs(self,newMechObjs):
try:
[obj.k for obj in newMechObjs]
except AttributeError:
raise AttributeError('argument mechObjs contains an invalid object')
else:
self._mechObjs = newMechObjs.tolist()[:]
@connPointMatrix.setter
def connPointMatrix(self,newConnPointMatrix):
try:
newConnPointMatrix[:,0]
except TypeError:
raise TypeError('argument connPointMatrix must be a 2D indexable object')
else:
self._connPointMatrix = np.asarray(newConnPointMatrix).copy()
@excPointMatrix.setter
def excPointMatrix(self,newExcPointMatrix):
try:
newExcPointMatrix[:,0]
except TypeError:
raise TypeError('argument excPointMatrix must be a 2D indexable object')
else:
self._excPointMatrix = np.asarray(newExcPointMatrix).cop()
# public methods
def calcModes(self):
self.__checkDimensions()
# private methods
def __checkDimensions(self):
if len(self.connPointMatrix[0,:]) != len(self.excPointMatrix[0,:]):
raise Exception('arguments connPointMatrix and excPointMatrix must contain an equal nr. of rows')
if len(self.connPointMatrix[0,:]) != len(self.mechObjs):
raise Exception('the nr. of rows of argument connPointMatrix must be equal to the nr. of\
elements in mechObjs')
if len(self.excPointMatrix[0,:]) != len(self.mechObjs):
raise Exception('the nr. of rows of argument excPointMatrix must be equal to the nr. of\
elements in mechObjs')
现在,当我创建一个新实例并尝试访问 mechObjs 属性时,我得到一个 AttributeError 并且我不明白为什么(其他两个属性相同)。在实例上调用 dir() 我可以看到包含列表和数组对象的 _mechObjs、_connPointMatrix 和 _excPointMatrix 属性。有人可以告诉我我在这里做错了什么吗?对象 FDString 是另一个自定义类,我省略了发布,因为源文件相当大。FDTimeBase 是一个只包含 2 个常量类属性的对象(没什么花哨的)。
提前致谢