Как класс наследуется от другого класса? Я пытаюсь реализовать его на следующем примере:Как класс наследуется от другого класса?
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
и sqNr
из parents
класса
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'
Я не понимаю, что не так в моей реализации, любое предложение?
а как насчет 'image_path'? Если я хочу изменить начальное значение? – Dalek
@ Далек же, как и любой другой аргумент по умолчанию, тоже пропустите: 'c = child (..., 'alternative_path')'. – jonrsharpe
+1 для композиции против наследования - важное различие. –