具有不同参数大小的多重继承

2024-10-05 13:31:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我想知道这是否可能。。。目前,我只有一份遗产。。。而且效果很好

在我的CiscoPlatform类中,我没有init方法,因此在创建对象时它需要6个参数(因为我使用的是BasePlatforminit方法)

我这样创建对象,效果很好:

ntw_device = []
device = CiscoPlatform(list[0],list[1],list[2],list[3],list[4],list[5])
ntw_device.append(device)

class BasePlatform(object):
     def __init__(self,ip,hostname,username,password,vendor,type):
         self.ip = ip
         self.hostname = hostname
         self.username = username
         self.password = password
         self.vendor = vendor
         self.type = type

class Cisco(BasePlatform,Interface):
     pass

我想介绍一个名为Interface的新基类

class Interface(object):
     def __init__(self,host,interface,vlan):
         self.host = host
         self.interface = interface
         self.vlan = vlan

我怎样才能继承两个具有不同参数数的父类?像这样的? *假设switchport=[]-对象列表

class CiscoPlatform(BasePlatform,Interface):
     def __init__(self):
          BaseClass.__init__(self,ntw_device[0].ip,ntw_device[1].hostname,ntw_device[2].username,ntw_device[3].password,ntw_device[4].vendor,ntw_device[5].type)
          Interface.__init__(self,switchport[0].Add to dictionary[1].interface,switchport[2].vlan)

当ciscopplatform不再接受6个参数时,我怎么还能以这种方式再次创建我的对象

device = CiscoPlatform(list[0],list[1],list[2],list[3],list[4],list[5])

Tags: selfipinitdevicetypeusernamepasswordinterface
1条回答
网友
1楼 · 发布于 2024-10-05 13:31:45

我不确定您的目的是否是确保CiscoPlatform类可以接受不同数量的参数,如果是这样的话,那就不难了。 初始化新的子类时,它的__init__()将被调用来初始化CiscoPlatform。因此,在决定应该使用哪个基类__init__之前,您只需要检查传入的参数的数量。
class CiscoPlatform(BasePlatform,Interface): def __init__(self, *arg): if len(arg) == 6: ip,hostname,username,password,vendor,type = arg
BaseClass.__init__(self,ip,hostname,username,password,vendor,type ) elif len(arg) == 3: host,interface,vlan = arg Interface.__init__(self,host,interface,vlan) else: raise ValueError("Inconsistent arguments number")

相关问题 更多 >

    热门问题