繁体   English   中英

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

[英]How could a class inherit from another class?

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

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级从parents级类继承prefixsqNr

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'

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

您需要在子类中调用超类的__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)

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实例。

请注意,根据样式指南 ,类名实际上应该是ParentChild

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM