我定义了以下父类:

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
我想要解释为什么我会收到此错误以及如何纠正该错误?

最佳答案

如果直接调用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`...

10-06 07:28