Dal*_*lek 2 python inheritance class subclass
一个类如何从另一个类继承?我正在尝试通过以下示例来实现它:
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))
Run Code Online (Sandbox Code Playgroud)
我想这个类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)
Run Code Online (Sandbox Code Playgroud)
并使用以下几行运行它,但我收到一条错误消息:
>>> 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'
Run Code Online (Sandbox Code Playgroud)
我不明白我的实施有什么问题,有什么建议吗?
将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
...
Run Code Online (Sandbox Code Playgroud)
这被称为:
c = child(300, 300, 'Test', 0)
Run Code Online (Sandbox Code Playgroud)
不需要创建parents实例,child直接创建即可。
请注意,根据样式指南,类名应该是Parent和Child。