이렇게하는 것이 가장 좋은 방법은 아니지만 가능합니다. 결국 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)
데모 : 인스턴스가 실제로 __new__()
방법 내에서 생성되는
>>> m1 = Matrix(2, 5)
Matrix(nrows=2, ncols=5)
>>> Matrix(1, 5)
Vector(nrows=1, ncols=5)
마음, __init__()
가 사용된다 새로 생성 된 인스턴스를 초기화합니다. 또한
, 통화 한 지하지
Vector
의
__init__()
방법과 같은 원치 않는 놀라움을 초래할 수있는 Matrix 클래스를 통해
Vector
인스턴스를 생성,
@Blckknght 아래의 코멘트에 언급 한 바와 같이이 (수동으로 호출 할 것이다) .
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
클래스의 (클래스/정적) 메서드로 구현 될 수 있지만 부모 클래스를 해당 하위 클래스 중 하나와 더 밀접하게 결합하게됩니다.
'__init__'으로 마법을 쓰려고하지 않고, 기준에 따라 클래스를 결정하는 팩토리를 사용하십시오. –