我正在尝试获取列表对象,而我的打印方法始终会返回空列表。我究竟做错了什么?看来
这是我想要的输出:
> NR
Enter a new name: R1
> NR
Enter a new name: R2
> NR
Enter a new name: R7
> C
Enter 1st router: R1
Enter 2nd router: R7
> C
Enter 1st router: R2
Enter 2nd router: R7
> P
Enter router name: R1
R1
N: R7
R:
> P
Enter router name: R2
R2
N: R7
R:
> P
Enter router name: R7
R7
N: R1, R2
R:
但是执行代码时我得到的只是空N:s。 像“ N:”
这是我的代码:
class Router:
def __init__(self, name):
self.__name = name
self.__neighbours = []
def add_neighbour(self, toadd):
self.__neighbours.append(toadd)
def print_info(self):
print(self.__name)
print("N:", end = " ")
print(*sorted(self.__neighbours))
print("R:")
routers = []
while True:
command = input("> ")
command = command.upper()
if command == "P":
toprint = input("Enter router name: ")
if toprint not in routers:
print("Router was not found.")
else:
Router(toprint).print_info()
elif command == "C":
router1 = input("Enter 1st router: ")
router2 = input("Enter 2nd router: ")
Router(router1).add_neighbour(router2)
Router(router2).add_neighbour(router1)
elif command == "RR":
pass
elif command == "NR":
newrouter = input("Enter a new name: ")
if newrouter in routers:
print("Name is taken.")
else:
routers.append(newrouter)