im a networking guy trying to learn some python to be able to automate. im having a difficult time grasping OOP. wrote the script below (not perfect i would assume) to experiment, and i keep getting the following as output:
main .Router object at 0x0000021C68033E80
my script:
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)
i understand that by printing the lists i just print where the memory pointer is pointing, but how do i make it so the values themselves are the ones actually being printed? thanks for the help!
You need to override the __repr__
method to change the string representation of the objects. Here's an example:
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.