如何使列表在 if 语句之外可访问?

How to make list accessible outside if statement?

我想访问if语句外的列表,python有静态函数吗?

列表是 switch1Flowswitch2Flowswitch3Flow

这是代码

def startingNode(self, destID, message, counter):
    pack =  self.pac.packet(self.name, destID, message) 
    if counter == "0":
        nextHop = self.controller.selectSwitch(self.name)
        print "Switch", self.name, "contacts controller"
        nextHop.receivePacket(pack)
        switch1Flow = [nextHop.name] //list1
        print switch1Flow
        nextHop1 = self.controller.selectSwitch(nextHop.name)
        print "Switch", nextHop.name, "contacts controller"
        nextHop1.receivePacket(pack)
        nextHop2 = self.controller.selectSwitch(nextHop1.name)
        print "Switch",nextHop1.name,"contacts controller"
        nextHop2.receivePacket(pack)
        switch2Flow = [self.name, nextHop1.name] // list2
        print switch2Flow
        switch3Flow = [nextHop.name, nextHop2.name] // list3
        print switch3Flow
    elif counter == "1":
        if 's2' in switch1Flow:
           print "forwarding to s2"
           if 's1' in switch2Flow and 's3' in switch2Flow:
             print "forwarding to s3"
             if 's2' in switch3Flow and 's4' in switch3Flow:
                 print "forwarding to s4"
                 print "message reched s4" 

我想在 elif.Can 中访问 switch1Flow、switch2Flow 和 switch3Flow,请告诉我如何访问?

if else 条件之外定义开关变量你应该没问题:

def startingNode(self,destID,message,counter):
    pack =  self.pac.packet(self.name,destID,message)
    switch1Flow = []
    switch2Flow = []
    switch3Flow = []
    if counter == "0":
        nextHop = self.controller.selectSwitch(self.name)
        print "Switch",self.name,"contacts controller"
        nextHop.receivePacket(pack)
        switch1Flow = [nextHop.name] //list1
        print switch1Flow
        nextHop1 = self.controller.selectSwitch(nextHop.name)
        print "Switch",nextHop.name,"contacts controller"
        nextHop1.receivePacket(pack)
        nextHop2 = self.controller.selectSwitch(nextHop1.name)
        print "Switch",nextHop1.name,"contacts controller"
        nextHop2.receivePacket(pack)
        switch2Flow = [self.name,nextHop1.name] //list2
        print switch2Flow
        switch3Flow = [nextHop.name,nextHop2.name] //list3
        print switch3Flow
    elif counter == "1":
        if 's2' in switch1Flow:
           print "forwarding to s2"
           if 's1' in switch2Flow and 's3' in switch2Flow:
             print "forwarding to s3"
             if 's2' in switch3Flow and 's4' in switch3Flow:
                 print "forwarding to s4"
                 print "message reched s4"