2014-09-28 1 views
0

클래스가 다른 클래스로부터 어떻게 상속받을 수 있습니까? 나는 다음의 예에 의하여이를 구현하기 위해 노력하고 있습니다 :클래스가 다른 클래스로부터 어떻게 상속받을 수 있습니까?

class parents(object): 
     def __init__(self,dim_x, dim_y, nameprefix, sequence_number): 
      if not isinstance(dim_x, (int, float, long)): 
      raise TypeError("Dimension in x must be a number") 
      else: 
      self.sizex=str(int(dim_x)) 
      if not isinstance(dim_y, (int, float, long)): 
      raise TypeError("Dimension in y must be a number") 
      else: 
      self.sizey=str(int(dim_y)) 
      if not isinstance(nameprefix, string_types): 
       raise TypeError("The name prefix must be a string") 
      else: 
       self.prefix=nameprefix 
      if not isinstance(sequence_number, (int, float, long)): 
      raise TypeError("The sequence number must be given as a number") 
      else: 
      self.sqNr=str(int(sequence_number)) 

내가 클래스 childprefixparents 클래스

class child(parents): 
     def __init__(self,image_path='/vol/'): 
     self.IMG_PATH=image_path 
     self.ref_image=self.prefix+'_R_'+self.sqNr 
     logger.debug('Reference image: %s', self.ref_image) 

에서 sqNr 상속하려면 다음과 같은 라인을 실행하지만,

>>> p=parents(300, 300, 'Test',0) 
>>> p.prefix 
'Test' 
>>> c=child(p) 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "<stdin>", line 4, in __init__ 
AttributeError: 'child' object has no attribute 'prefix' 

내 구현, 어떤 잘못이 무엇인지 이해가 안 : 나는 오류 메시지가 제안?

답변

3

childparents에 대한 모든 인수를 가져와 함께 전달해야합니다. 일반적으로 수퍼 클래스 인스턴스를 서브 클래스에 전달하지 않습니다. 그게 인데,이 아니라 의 계승 인입니다.

class child(parents): 
    def __init__(self, dim_x, dim_y, nameprefix, 
       sequence_number, image_path='/vol/'): 
     super(child, self).__init__(dim_x, dim_y, nameprefix, 
            sequence_number) 
     self.IMG_PATH = image_path 
     ... 

다음이라고합니다 : 당신은 직접 child을 만듭니다 parents 인스턴스를 만들 필요가 없습니다

c = child(300, 300, 'Test', 0) 

.

style guide 당 클래스 이름은 실제로 ParentChild이어야합니다.

+0

그리고'image_path'는 어떻게됩니까? 초기 값을 변경하고 싶습니까? – Dalek

+0

@Dalek 다른 기본 인수와 동일하게 'c = child (...,'alternative_path ')'를 전달하십시오. – jonrsharpe

+3

+1 대 구성 - 중요한 구분. –

3

하위 클래스에서 수퍼 클래스 '__init__ 메서드를 호출해야합니다.

class child(parents): 
    def __init__(self,image_path='/vol/'): 
     super(child, self).__init__(...) # dim_x, dim_y, nameprefix, sequence_number 
     .... 

파이썬 3.x를, 당신은 대신 super(child, self)super() 사용할 수 있습니다.

+0

어떻게 두 번째 클래스를 호출 할 수 있습니까? – Dalek

+0

@Dalek, 당신은'어린이 '클래스를 의미합니까? '__init__'에? – falsetru

+0

예! 'super (child, self) .__ init __ (self, dim_x, dim_y, nameprefix, sequence_number)'와 같아야합니까? – Dalek

관련 문제