使用超级方法计算 class 参数

Calculating a class parameter using a super method

我是 Python 的新手,正在尝试了解执行以下操作的最正确方法:

我有一个名为 "Sample" 的基 class。它有dp,tp等一些属性

我还有几个子class从这个基础派生出来的样本A、样本B等。它们有几个不同的属性。其中一个属性是使用这些独特的属性计算出来的。而且这个计算是相当重复的,所以我想写一个方法并在每个class中调用它来计算参数的值。

class Sample(object):
    tp = 4
    dp = 4.2
    por = 0.007

    def common_method(self, arg1, arg2)
        return self.tp - arg1 * arg2

class SampleA(Sample)
    arg1 = 0.1
    arg2 = 2
    # I want to calculate arg3, but I don't know how to call the         
    # common_method here.

class SampleB(Sample)

.
.
.

提问前查了一下,没看到类似的问题。

非常感谢您提前告知。

这可能是元class有意义的罕见情况之一。

class CommonProperty(type):
    @property
    def common_property(cls):
        return cls.tp - cls.arg1 * cls.arg2

class Sample(object, metaclass=CommonProperty):
    tp = 4

class SampleA(Sample):
    arg1 = 0.2
    arg2 = 2

print(SampleA.common_property) # 3.6

想法是将一个property分配给子class继承并完成的元class。 metaclass 在这里很自然,因为目标是创建 class property 而不是实例 property 而 class 是 metaclass.

解决方案由dhke在原问题的评论中提出:

common_method() needs an object, but you are still in the class declaration. Has common_method() any other use? Because then you could just make it a class method and refer to it by Sample.common_method()

将其应用到代码中会更好,我认为:

class Sample(object):
    tp = 4
    dp = 4.2
    por = 0.007

@classmethod
def common_method(self, arg1, arg2)
    return self.tp - arg1 * arg2

class SampleA(Sample)
    arg1 = 0.1
    arg2 = 2
    arg3 = Sample.common_method(arg1, arg2)  # 3.8

class SampleB(Sample):

.
.
.

非常感谢你帮我解决这个问题!