Python - List and Loop in one def
I'm trying to get the def wfsc_pod1 and wfsc_ip into the same def. I'm not quite sure how to approach the problem. I want wfsc_pod1 to display all the information for name, subnet and gateway. Then wfsc_ip shows the ip addresses below it. I also get a None value when I run it as it. Not sure why. Anything more pythonic is more appreciated.
class OutageAddress:
subnet = ["255.255.255.0", "255.255.255.1"]
# Gateway order is matched wi开发者_开发知识库th names
gateway = ["192.168.1.1", "192.168.1.2", "192.168.1.3", "192.168.1.4",
"192.168.1.5", "192.168.1.6", "192.168.1.7", "192.168.1.8",
"192.168.1.9"]
name = ["LOC1", "LOC2", "LOC3", "LOC4",
"LOC5", "LOC6", "LOC7", "LOC8",
"LOC9"]
def wfsc_pod1(self):
wfsc_1 = "%s\t %s\t %s\t" % (network.name[0],network.subnet[0],network.gateway[0])
return wfsc_1
def wfsc_ip(self):
for ip in range(100,110):
ip = "192.168.1."+str(ip)
print ip
network = OutageAddress()
print network.wfsc_pod1()
print network.wfsc_ip()
First of all, you probably meant to write wfsc_pod1
like this:
def wfsc_pod1(self):
return "%s\t%s\t%s" % (self.name[0], self.subnet[0], self.gateway[0])
and call wfsc_ip
like this:
network.wfsc_ip() # no print
If you want to combine wfsc_pod1
and wfsc_ip
, you can do this:
def wfsc_combined(self):
output = []
output.append("%s\t%s\t%s" % (self.name[0], self.subnet[0], self.gateway[0]))
for ip in range(100,110):
output.append("192.168.1.%d" % ip)
return '\n'.join(output)
and call this function with a print statement.
However, a better approach (IMO) would be to add print statements inside wfsc_combined
and call it without a print statement:
def wfsc_combined(self):
print "%s\t%s\t%s" % (self.name[0], self.subnet[0], self.gateway[0])
for ip in range(100,110):
print "192.168.1.%d" % ip
OutageAddress.wfsc_ip
returns None
because it has no return statement.
You get a None
because that is what wfsc_ip
returns. Functions/methods that don't return anything else return None
.
You get None
from print network.wfsc_ip()
because wfsc_ip
doesn't return anything, which is the same thing as returning None
-- what else did you expect to get from printing the value of a function that just doesn't return anything?!
You seem to be in thrall to a deep confusion between displaying stuff (e.g. with print
statements, as wfsc_ip
does) and returning information, as wfsc_pod1
does. Until and unless you clarify that confusion, nobody can really help you much.
精彩评论