简体   繁体   中英

How could a class inherit from another class?

How could a class inherit from another class? I am trying to implement it by the following example:

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

I want that the class child inherits the prefix and the sqNr from the parents class

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)

And run it with the following lines, but I get an error message:

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

I don't understand what is wrong about my implementation, any suggestion?

You need to call superclass' __init__ method in child class.

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

In Python 3.x, you can use super() instead of super(child, self) .

The child needs to take all of the arguments for the parents , and pass them along. You don't generally pass a superclass instance to the subclass; that's composition , not inheritance .

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

This is then called:

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

You don't need to create a parents instance, create the child directly.

Note that, per the style guide , the class names should really be Parent and Child .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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