我試圖以高效和Pythonic的方式在類(包括它們的初始值設定項)和方法中實現重複的功能。Python類,初始值設定項和方法中的重複功能/代碼
我是繼承和覆蓋方法(如看到here)。我有櫃檯定義和增強每個類的作業。
我的代碼
class StructuralAnalysis(object):
def __init__(self):
self.counter_results = [] # probably a dict would be better
def generate_structural_metrics(self):
# declare counters
cnum = 0
cstr = 0
cbytes = 0
...
...
...
for node in ast.walk(self.tree):
if isinstance(node, ast.Num):
cnum += 1
elif isinstance(node, ast.Str):
cstr += 1
elif isinstance(node, ast.Bytes):
cbytes += 1
elif ...
elif ...
elif ...
self.counter_results = [cnum, cstr, cbytes, .......]
# some counters may require some further calculations
return self.counter_results
我的問題是上述可以以更Python和/或有效的方式來實現;就像每個計數器有不同的類方法,每個重寫的方法將調用它來執行增強的分配?這是爲了避免大量的計數器聲明和重複代碼。任何建議都會很棒。
您是否正在尋找python中的元編程? – biobirdman
@biobirdman不知道那是什麼。只是探索在類中實現重複功能的'最佳'方法真的.. –