2017-08-08 63 views
-1

我是新來的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

回答

0

解決方案由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): 

. 
. 
. 

非常感謝你對我的幫助與此!

0

這可能是元類有意義的罕見實例之一。

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,而類是元類的實例。