If I make a list in one function, and edit it, then I want to be able to pass the finished list off to another function where it will be used to do more things.
def func1():
numbers = [1, 2, 3, 4]
if numbers.count(1) > 0:
numbers.remove(1)
func2()
def func2():
two = numbers[0]
func1()
How could I get it so that it doesn't pull the error numbers not defined globally. I know why it is pulling the error, but after researching, I still can't find a good way to fix this problem.
解决方案
Based on your mileage and requirement, choose one
Pass the list as a parameter to the called function
def func2(numbers):
two = numbers[0]
def func1():
numbers = [1, 2, 3, 4]
if numbers.count(1) > 0:
numbers.remove(1)
func2(numbers)
Make both the functions part of a single Class and make the list an instance attribute
class Foo(object):
def __init__(self, numbers):
self.numbers = numbers
pass
def func1(self):
if self.numbers.count(1) > 0:
self.numbers.remove(1)
self.func2()
def func2(self):
two = self.numbers[0]
Foo([1, 2, 3, 4]).func1()
Redesign so that the called function is decorated with the caller
def func1(func):
def wraps(*argv):
numbers = argv[0]
if numbers.count(1) > 0:
numbers.remove(1)
func(*argv)
return wraps
@func1
def func2(numbers):
two = numbers[0]
func2([1,2,3,4])
Closure with nested function
def func1():
def func2():
two = numbers[0]
numbers = [1, 2, 3, 4]
if numbers.count(1) > 0:
numbers.remove(1)
func2()
func1()