我是一个尝试学习一些python能够自动化的网络专家。我在掌握OOP时遇到了困难。写了下面的脚本(我认为不是很完美)进行实验,并且我不断得到以下内容作为输出:
主路由器对象位于0x0000021C68033E80
我的脚本:
class Router:
name=''
def __init__(self,ip,network):
self.ip = ip
self.network=network
def getip(self):
print(self.ip)
def getname(self):
print(self.name)
def getnetwork(self):
print(self.network)
class Switch(Router):
def __init__(self,ip,network,layer):
Router.__init__(self,ip,network)
self.layer=layer
self.vlans=[]
def addvlan(self,vlan):
self.vlans.append(vlan)
def getvlans(self):
print(self.vlans)
def getlayer(self):
print(self.layer)
routers=[]
switches=[]
while(True):
rors = ""
while(rors != "router" and rors!= "switch" and rors != "0"):
rors = input("router or switch? 0 to exit: ")
if(rors=="router"):
routers.append(Router(input("enter ip: "),input("enter network: ")))
elif(rors=="switch"):
switches.append(Switch(input("enter ip: "),input("enter network: "),input("layer?: ")))
stop=1
while(stop!=0):
stop=int(input("enter 1 to continue, 0 to stop adding vlans: "))
if(stop==0):break
switches[len(switches)-1].addvlan(int(input("add vlan: ")))
elif(rors == "0"):
break
else: print("input error")
print(switches)
print(routers)
我知道通过打印列表,我只打印内存指针指向的位置,但是我该如何使值本身真正被打印呢?谢谢您的帮助!
您需要重写__repr__
方法以更改对象的字符串表示形式。这是一个例子:
In [1]: class A1:
...: def __init__(self, a, b):
...: self.a = a
...: self.b = b
...:
In [2]: class A2:
...: def __init__(self, a, b):
...: self.a = a
...: self.b = b
...: def __repr__(self):
...: kvps = [f"{k}={v}" for k, v in vars(self).items()]
...: return f"{type(self).__name__}({', '.join(kvps)})"
...:
In [3]: A1(1, 2)
Out[3]: <__main__.A1 at 0x7f533357fe20>
In [4]: A2(1, 2)
Out[4]: A2(a=1, b=2)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句