【问题标题】:How do I refer to the "return" of a function in a method from another class in Python?如何在 Python 中的另一个类的方法中引用函数的“返回”?
【发布时间】:2017-03-26 19:19:51
【问题描述】:

这是我的代码:

class MetricTensor:  #The Metric Tensor Class
    def __init__(self, g0, g1, g2, g3, g4, g5, g6, g7, g8, g9, g10, g11, g12, g13, g14, g15): #Metric components
        self.g0 = g0
        self.g1 = g1
        self.g2 = g2
        self.g3 = g3
        self.g4 = g4
        self.g5 = g5
        self.g6 = g6
        self.g7 = g7
        self.g8 = g8
        self.g9 = g9
        self.g10 = g10
        self.g11 = g11
        self.g12 = g12
        self.g13 = g13
        self.g14 = g14
        self.g15 = g15

    def LMetric(self):
        lmetric = [self.g0, self.g1, self.g2, self.g3, self.g4, self.g5, self.g6, self.g7, self.g8, self.g9, self.g10, self.g11, self.g12, self.g13, self.g14, self.g15]
        return list(lmetric)

    def Mmetric(self,lmetric):
        mmetric = np.matrix([lmetric[0],lmetric[1],lmetric[2],lmetric[3], [lmetric[4],lmetric[5],lmetric[6],lmetric[7]], [lmetric[8],lmetric[9],lmetric[10],lmetric[11]], [lmetric[12],lmetric[13],lmetric[14]],lmetric[15]])
        return mmetric

    def InvMmetric(self,mmetric):
         invmmetric =  self.np.linalg.inv(mmetric)
         return invmmetric
    def LInvMetric(self,invmmetric):
        linvmetric = list(invmmetric)
        return linvmetric

class ChristoffelSymbol(MetricTensor):
    def __init__(self,a, b, c):
        self.a = a
        self.b = b
        self.c = c
        Ca = None
        for k in numcoords:
            Ca += 1/2*(linvmetric)

注意 MetricTensor 类的最后一个方法:LInvmetric,该函数返回:linvmetric.

我的问题是: 如何在新类 (ChristoffelSymbol) 中使用此返回 (linvmetric),它是第一个 (MetricTensor) 的子类?

更准确地说,如何在linvmetric中只使用一个元素(既然是列表,我想用linvmetric[0]为例)?

【问题讨论】:

  • numpy 已被导入为“np”
  • what_i_want, *_ = self.LInvMetric(invmmetric)

标签: python class methods return call


【解决方案1】:

经过讨论更新答案:

您还需要调用在MetricTensor 类中定义的方法。下面的代码就是这样做的:

mt = MetricTensor("...args...")  # args here are all the metric components
lmetric = mt.LMetric()
mmetric = mt.Mmetric(lmetric)
invmmetric = mt.InvMmetric(mmetric)
linvmetric = mt.LInvMetric(invmetric)

现在linvmetric 可以在更多代码中使用。

【讨论】:

    【解决方案2】:

    只需使用self,因为它继承自 MetricTensor

    self.LInvMetric() - will get you the full list
    self.LInvMetric()[0]  - first elem and so on
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-27
      • 2022-09-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多