使用超级方法

问题描述:

我是新来的Python,并试图了解什么是做到以下几点是最正确的方法计算类参数。它有一些属性,如dp,tp等。使用超级方法

我也有几个从这个基类派生的子类,如SampleA,SampleB等。它们有几个不同的属性。其中一个属性使用这些独特的属性进行计算。这个计算是相当重复的,因此我想写一个方法并在每个类中调用它来计算参数的值。

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) 

. 
. 
. 

在问这个问题之前,我查了一下但我没有看到类似的问题。

谢谢你提前很多。

+2

'common_method()'需要一个对象,但是你仍然在类声明中。有'common_method()'任何其他用途?因为那样你就可以将它变成[类方法](https://docs.python.org/2/library/functions.html#classmethod),并通过'Sample.common_method()'引用它。 – dhke

+0

Python 2或Python 3? –

+0

@dhke我考虑只在类中使用common_method。 – mutotemiz

解决方案由dhke在原来问题的意见提出:

common_method()需要一个对象,但你仍然在类的声明。有common_method()有其他用途吗?因为那样的话,你可以只让一个class methodSample.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): 

. 
. 
. 

非常感谢你对我的帮助与此!

这可能是元类有意义的罕见实例之一。

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分配到已进行遗传和完成了由子类元类。元类在这里很自然,因为目标是创建类property而不是实例property,而类是元类的实例。