これは実行するのが最善の方法ではないかもしれませんが、これを行うことができます。結局のところ、Matrix
クラスがインスタンス化されている場合、結果はMatrix
インスタンスになると予想されます。
ことを達成する一つの方法は、Matrix
クラスのコンストラクタをカスタマイズすることです:
class Matrix:
def __new__(cls, nrows, ncols):
if nrows == 1:
inst = super(Matrix, cls).__new__(Vector)
else:
inst = super(Matrix, cls).__new__(cls)
inst.nrows = nrows
inst.ncols = ncols
return inst
def __repr__(self):
return '{}(nrows={}, ncols={})'.format(
self.__class__.__name__, self.nrows, self.ncols)
デモ:__init__()
が使用されている間、インスタンスは実際に、__new__()
メソッド内で作成され
>>> m1 = Matrix(2, 5)
Matrix(nrows=2, ncols=5)
>>> Matrix(1, 5)
Vector(nrows=1, ncols=5)
マインド新しく作成されたインスタンスを初期化します。また
、@Blckknghtにより以下のコメントで述べたように、Matrixクラスを通じてVector
インスタンスを作成することは、(それが手動で呼び出されなければならないだろう)と呼ばれるばかりではないVector
の__init__()
方法のように、不要な驚きにつながることができます。
class Matrix:
def __init__(self, nrows, ncols):
self.nrows = nrows
self.ncols = ncols
def __repr__(self):
return '{}(nrows={}, ncols={})'.format(
self.__class__.__name__, self.nrows, self.ncols)
class Vector(Matrix):
pass
def make_matrix(nrows, ncols):
if nrows == 1:
return Vector(nrows, ncols)
return Matrix(nrows, ncols)
デモ:もちろん
>>> make_matrix(1, 5)
Vector(nrows=1, ncols=5)
>>> make_matrix(2, 5)
Matrix(nrows=2, ncols=5)
ユースケースによっては、しかし、このようにきれいなものを維持し、単にインスタンスの作成のために工場を使用する方がよいかもしれませんmake_matrix()
は、Matrix
クラスの(クラス/静的)メソッドとして実装することもできますが、それは親クラスをその子クラスの1つと密接に結合させるでしょう...
'__init__で魔法をしようとするのではなく、あなたの基準に基づいてクラスを決定するファクトリを使用してください。 –