如何定义类的层次结构来继承变量和方法?

2024-09-28 23:00:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图找到一种有效的(代码长度、冗长、可读性)方法来实现材质属性数据库。有时会对不同的属性进行分组。例如,所有材料都有疲劳寿命,不同的材料类型有不同的抗疲劳性,不同的材料等级有不同的刚度。你知道吗

class Material(object):

    def convert_c_to_f(self, temperature):
        blah = (temperature - 32) *5.0 / 9.0
        return blah

    def other_function(self, foobar):
        return foobar

class CarbonSteel(Material):
    def __init__(self):
        super(CarbonSteel, self).__init__()

    prop_one = 3.0
    prop_two = 0.2

    fatigue_constants = [     2.254510, -4.642236e-01, -8.312745e-01,
                          8.634660e-02,  2.020834e-01, -6.940535e-03,
                         -2.079726e-02,  2.010235e-04, 7.137717e-04,
                             0.0,                 0.0]

class SA105(CarbonSteel):

    def __init__(self):
        super(SA105, self).__init__()

    units = "imperial"

    nom_comp = "Carbon Steel"
    form = "Forging"
    P_no = "1"
    group = "2"

    min_tensile_ksi = 70
    min_yield_ksi = 36

    temp_list = [-20.0, 400.0, 500.0, 600.0, 650.0, 700.0, 750.0, 800.0, 850.0, 900.0, 950.0, 1000.0]
    temp_list = np.array(temp_list)

则以下操作失败:

    temp_list_c = temp_f2c(temp_list)
    temp_list_c = super().super().temp_f2c(temp_list)

当我把我的对象定义为

self.material = SA105()

那我就不能进去拿“超级”房产了:

self.material.super().fatigue_constants

现在我有点迷路了。我试着用这些方法做很多事情,引用继承的方法和变量,但是我有点迷路了。你知道吗

希望避免将所有数据复制到每个类中,然后在发现错误时必须更改多个位置中的错误。我主要使用类是因为它们的继承属性,但是可能有更好的方法。(如果不需要方法,我可以想出一些)

谢谢!你知道吗

编辑:试图提供一些更具体的例子。在不复制大量代码的情况下尝试这样做。如果我不应该使用类,那么让我知道。。。你知道吗


Tags: 方法代码self属性initdeftemplist