在Python中使用另一个对象初始化对象

2024-09-30 18:25:16 发布

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

我有以下代码:

import xmlrpc.client as xc
class AristaSwitch():
    def __init__(self,devicename,user='admin',password='xxxxxx')
        self.url="https://"+user+":"+password+"@"+devicename+"/command-api"
        self.Server = xc.Server(self.url)     **<----i know this is not correct** 
    more code below here

我希望能够像下面这样编写代码:

as = AristaSwitch("192.168.1.1")
as.runCmds(1, [ "show hostname" ] )

他们的做法是:

import xmlrpc.client as xc
switch = xc.Server( "https://admin:admin@172.16.130.16/command-api" ) 
response = switch.runCmds( 1, [ "show hostname" ] ) 

更新 我认为把它添加到init函数中就可以了

    self.InitializeRPCServer()
def InitializeRPCServer():
    switch=xc.Server(self.url)
    return switch

Tags: 代码importselfclienturlserveradmininit
1条回答
网友
1楼 · 发布于 2024-09-30 18:25:16

似乎你只是想绕着xc.Server转。只需使用函数而不是类

import xmlrpc.client as xc
def AristaSwitch(devicename, user='admin', password='xxxxxx'):
    url="https://"+user+":"+password+"@"+devicename+"/command-api"
    Server = xc.Server(url)
    return Server

那就做你该做的:

as = AristaSwitch("192.168.1.1")
as.runCmds(1, [ "show hostname" ] )

如果要自定义xc.Server对象,可以直接继承它:

class AristaSwitch(xc.Server):
    def __init__(self, devicename, user='admin', password='xxxxxx'):
        self.url="https://"+user+":"+password+"@"+devicename+"/command-api"
        super().__init__(self.url)

您需要将def __init__更新为定制的url输入,但是您应该非常了解原始实现,因为您可能无意中覆盖了超类xc.Server中的某些属性或实现细节

在这个用例中,AristaSwitch基本上是带有定制实例化方法的xc.Server,如果您愿意,您可以稍后使用自己的方法来补充它

相关问题 更多 >