【问题标题】:How could a class inherit from another class?一个类如何继承另一个类?
【发布时间】:2014-11-22 22:26:45
【问题描述】:

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

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'

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

【问题讨论】:

    标签: python class inheritance subclass


    【解决方案1】:

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

    【讨论】:

    • 我怎么叫二等舱?
    • @Dalek,你是说child 类吗?在__init__ ?
    • 是的!应该是:super(child, self).__init__(self,dim_x, dim_y, nameprefix, sequence_number)
    • 这是标准吗?就像你总是必须调用 super ASWELL 一样把父类作为类的参数?
    • @Totem 父类属性通常不应该是子类初始化器的参数
    【解决方案2】:

    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

    【讨论】:

    • 那么image_path 呢?如果我想改变一个初始值?
    • @Dalek 与任何其他默认参数相同,也传递它:c = child(..., 'alternative_path')
    • @jonrsharpe 我有一个问题:如果我有 Parent 类的函数,并且我想在 Child 类中运行它,然后再在 Child 类中使用它的结果,我该怎么办?
    • @Dalek 方法由Child 继承,只需使用c.method(外部)或self.method(内部),就像它们直接在Child 中定义一样。如果您定义了Child.method,则需要再次使用super 才能访问Parent.method
    • @Dalek 该方法是否也在孩子中实现?!如果没有,只需self.run(...)
    猜你喜欢
    • 1970-01-01
    • 2014-10-08
    • 2019-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-13
    • 2014-04-14
    相关资源
    最近更新 更多