一个类如何从另一个类继承?

时间:2014-09-28 11:36:48

标签: python class inheritance subclass

一个类如何从另一个类继承?我试图通过以下示例实现它:

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))

我希望课程child继承prefix课程中的sqNrparents

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)

使用以下行运行它,但我收到一条错误消息:

>>> 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'

我不明白我的实施有什么问题,有什么建议吗?

2 个答案:

答案 0 :(得分:3)

您需要在子类中调用超类'__init__方法。

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

在Python 3.x中,您可以使用super()代替super(child, self)

答案 1 :(得分:3)

child需要获取parents的所有参数,然后传递它们。您通常不会将超类实例传递给子类;那个组合,而不是继承

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
        ...

然后调用:

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

您不需要创建parents实例,直接创建child

请注意,根据style guide,类名应该是ParentChild