一个类如何从另一个类继承?我试图通过以下示例实现它:
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'
我不明白我的实施有什么问题,有什么建议吗?
答案 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,类名应该是Parent
和Child
。