我定义了以下父类:
class Material(object):
def newMaterial(self,matPhysLaw, stressState,e,nu,alpha,sigY = 0.0,kM = 0.0,mM = 0.0):
if (matPhysLaw=="elastic"):
return ElasticMaterial(self,stressState,e,nu,alpha,sigY,kM,mM)
以下儿童班:
class ElasticMaterial(Material):
def __init__(self,StressState,e,nu,alpha,sigY=0.0,kM=0.0,mM=0.0):
#Material.__init__(self,StressState,e,nu,alpha,sigY=0.0,kM=0.0,mM=0.0)
self.StressState = StressState
if self.StressState=='threed':
self.lv=6 #lv is length of stress and strain vectors
else:
self.lv=4
self.e = e
self.nu = nu
self.alpha = alpha
self.sigY = sigY
self.kM = kM
self.mM = mM
我正在尝试从基类本身创建子类,我正在调用newMaterial()
方法,如下所示:
m2 = Material.newMaterial('elastic','threed',10e6,0.2,1e7)
但是,我收到的错误为newMaterial() is missing 1 positional argument: alpha
。
我想解释为什么我会收到此错误,我该如何纠正?
答案 0 :(得分:1)
如果您直接调用Material.newMaterial(...)
,则self
不受约束,因此您错过了强制性参数。 (您正试图通过newMaterial
等方式致电self='elastic'
。)
删除参数并将其设为@staticmethod
:
class Material(object):
@staticmethod
def newMaterial(matPhysLaw, stressState, e, nu, alpha, sigY=0.0, kM=0.0, mM=0.0):
if matPhysLaw == "elastic":
# But here you don't need the `self` parameter for instantiation
return ElasticMaterial(stressState, e, nu, alpha, sigY, kM, mM)
如果您需要保留对该类的引用,请使用@classmethod
装饰器:
class Material(object):
@classmethod
def newMaterial(cls, matPhysLaw, stressState, e, nu, alpha, sigY=0.0, kM=0.0, mM=0.0):
if (matPhysLaw=="elastic"):
return ElasticMaterial(stressState, e, nu, alpha, sigY, kM, mM)
# Do something with `cls`...