私はほとんど同じ方法で部分的に初期化する必要があるさまざまなクラスを持っています。 init関数は、入力ファイルパスおよび/またはnumpyデータを入力します。同様の方法で異なるクラスを初期化する
class InertialData1:
def __init__(self, file=None, data=None):
# --- this is the (almost) common part ---
if file is None:
self.file = 'Unknown path to file'
else:
self.file = file
assert isinstance(self.file, str)
if data is None:
self.data = read_logfile(file, 'a_token')
else:
self.data = data
assert isinstance(self.data, np.ndarray)
# --- end of the common part ---
# Here other stuff different from class to class
read_logfile()関数(外部関数)のトークンもクラスからクラスに変更されます。
class InertialData2:
def __init__(self, file=None, data=None):
# here the common code as above, but with 'another_token' instead of 'a_token'
# here other stuff
...
もちろん、すべてのクラス定義で同じ行を書くことはもちろん不可能です。
可能な解決策。
私はその後、私はこのように、各クラスののinitメソッド内でそれを使用することができ、この
def initialize(file, data, token):
if file is None:
file = 'Unknown path to file'
else:
file = file
assert isinstance(file, str)
if data is None:
data = read_logfile(file, token)
else:
data = data
assert isinstance(data, np.ndarray)
return file, data
のような外部関数の定義について考えた:
class InertialData1:
def __init__(self, file=None, data=None):
self.file = file
self.data = data
self.file, self.data = initialize(self.file, self.data, token='a_token')
をこの方法では、動作しているようです。私はちょうどそれを行うのに最適な方法ではない、またはpythonicではないと感じている、あなたの答えから何かを学ぶことを願っています:) ありがとう
ご返信ありがとうございます。しかし、それはこのように動作していないようです。 TypeError:superはキーワード引数を受け取りません – Robyc
「super」が渡された引数を自動的に再利用することを忘れていました。また、 'data'を' init_data'メソッドに渡す必要があることを認識しました。そのコードも –
'super'だけでも動作していません。 'super().__ init __(file、data)'が動作しています。 しかし、私はこのような基本的なinit関数を呼び出すことをお勧めします。 – Robyc