2017-12-06 11 views
0

부모 클래스와 아이디어에 대한보다 구체적인 정보를 포함하여 상위 클래스를 확장하는 여러 자식 클래스가 있다고 가정합니다. 그들은 나타냅니다. 예를 들어 :Python 3 : 자식 생성자가 부모 생성자보다 많은 인수를 가질 때 상속 된 메서드에서 새 하위 클래스 인스턴스 반환

class Shape: 
    def __init__(self, center): 
     self.center = center 


class Square(Shape): 
    def __init__(self, center, side_length): 
     super().__init__(self, center) 
     self.side_length = side_length 
     self.area = side_length ** 2 


class Circle(Shape): 
    def __init__(self, center, radius): 
     super().__init__(self, center) 
     self.radius = radius 
     self.area = 3.14 * (radius ** 2) 

은 가정하자 나는 원래 목적과는 다른 중앙 위치에 새 개체를 반환 부모 클래스의 메소드와 같은 translate(new_center)를 구현하고자합니다. 모든 하위 클래스가 동일한 방식으로 동작해야하므로 (예 : self.center 속성이 변경되어야 함) translate()을 부모 클래스 Shape의 메소드로 구현하는 것이 좋습니다. 하위 클래스 인스턴스이를 호출하는 경우,

def translate(self, new_center): 
     return Shape(new_center) 

그러나 : 나는라고 유형 Shape마다 translate()의 새로운 객체를 반환하려면

, 우리는 단순히 때문에 같은 Shape의 방법으로 translate()을 정의 할 수 있습니다 메서드를 사용하면 결과는 Shape 유형이므로 원래 인스턴스에 포함 된 추가 상태 정보 (예 : Squareside_lengtharea)는 손실됩니다. 자식 클래스의 각 생성자는 부모 클래스 생성자하지 않는 것을 추가 인수를 필요로하기 때문에 또한, translate()

def translate(self, new_center): 
     return self.__class__(new_center) 

로 정의 할 수 없습니다. 어떻게 각 하위 클래스의 부모 메서드를 재정의 할 필요없이 구현할 수 있습니까? (부모 메서드를 정의하는 전체 지점을 피하는 방법)?

답변

2

당신은 객체를 복사 수정할 수 :

import copy 

class Shape(): 
    def __init__(self, center): 
    self.center = center 

    def translate(self, new_center): 
    new_shape = copy.copy(self) # Replace with deepcopy if needed 
    new_shape.center = new_center 

...