我是新來的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)
.
.
.
在問這個問題之前,我查了一下但我沒有看到類似的問題。
謝謝你提前很多。
'common_method()'需要一個對象,但是你仍然在類聲明中。有'common_method()'任何其他用途?因爲那樣你就可以將它變成[類方法](https://docs.python.org/2/library/functions.html#classmethod),並通過'Sample.common_method()'引用它。 – dhke
Python 2或Python 3? –
@dhke我考慮只在類中使用common_method。 – mutotemiz