gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 08:09:09 26 4
gpt4 key购买 nike

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

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'

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

最佳答案

child 需要为 parents 获取所有参数,并将它们一起传递。您通常不会将父类(super class)实例传递给子类;那是组合,而不是继承

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

关于python - 一个类如何从另一个类继承?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26084470/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com