Python中用于在函数之间共享值的全局变量的替代方案是什么



我通常听说在编程时使用全局变量是一种糟糕的做法。那么,除了我在这里试图做的,即在另一个函数中使用变量my_array,还有其他选择吗?

import random
def main():  
    create_list_and_find_max_and_min(10)  
    the_smart_way()
def create_list_and_find_max_and_min(n):
    global my_array
    my_array = []
    n = input("How many numbers do you want in your array?:")
    for i in range(n):
        my_array.append(random.randint(1,n))
    print "My array is:", my_array
    min = my_array[0]
    for number in my_array:
    if min > number:
        min = number
    print "The minimum value in the array is:", min
    max = my_array[0]
    for number in my_array:
        if max < number:
        max = number
    print "The maximum value in the array is:", max
def the_smart_way():
    # "This one uses the built-in Python functions for min/max..."
    min_my_array = min(my_array)
    max_my_array = max(my_array)
    return min_my_array, max_my_array
if __name__ == '__main__':
    main()

是的,有两种选择。

首先,您可以四处传递值,而不是使用全局值。例如,create_list_and_find_max_and_min可以在本地创建数组并返回它,然后您可以将它传递给the_smart_way:

import random  
def main():  
    my_array = create_list_and_find_max_and_min(10)  
    print the_smart_way(my_array)
def create_list_and_find_max_and_min(n):
    my_array = []
    n = input("How many numbers do you want in your array?:")
    for i in range(n):
        my_array.append(random.randint(1,n))
    print "My array is:", my_array
    min = my_array[0]
    for number in my_array:
        if min > number:
            min = number
    print "The minimum value in the array is:", min
    max = my_array[0]
    for number in my_array:
        if max < number:
            max = number
    print "The maximum value in the array is:", max
    return my_array
def the_smart_way(my_array):
    # "This one uses the built-in Python functions for min/max..."
    min_my_array = min(my_array)
    max_my_array = max(my_array)
    return min_my_array, max_my_array
if __name__ == '__main__':
    main()

其次,您可以创建一个类来封装数据和对该数据进行操作的函数:

import random  
class MyArrayClass(object):
    def create_list_and_find_max_and_min(self, n):
        self.my_array = []
        n = input("How many numbers do you want in your array?:")
        for i in range(n):
            self.my_array.append(random.randint(1,n))
        print "My array is:", self.my_array
        min = self.my_array[0]
        for number in self.my_array:
            if min > number:
                min = number
        print "The minimum value in the array is:", min
        max = self.my_array[0]
        for number in self.my_array:
            if max < number:
                max = number
        print "The maximum value in the array is:", max
    def the_smart_way(self):
        # "This one uses the built-in Python functions for min/max..."
        min_my_array = min(self.my_array)
        max_my_array = max(self.my_array)
        return min_my_array, max_my_array
def main():
    my_array = MyArrayClass()
    my_array.create_list_and_find_max_and_min(10)  
    print my_array.the_smart_way()
if __name__ == '__main__':
    main()

您可能应该理解全局变量是错误做法的原因。

想象一下,您想要创建两个数组。有了全局变量,第二个变量将取代第一个变量,第一个变量将永远消失。

create_list_and_fix_max_and_min(10)
create_list_and_fix_max_and_min(20)
# No way to operate on the original array!

使用本地变量,您可以同时存储这两个变量:

my_array_1 = create_list_and_fix_max_and_min(10)
my_array_2 = create_list_and_fix_max_and_min(20)
the_smart_way(my_array_1)

使用一个对象也有同样的好处;两者之间的区别最终归结为操作是否是数据含义的一部分,或者数据是否独立,操作是否通用。(或者,有时,无论你是一个功能势利者还是OO势利者…)

函数对对象执行操作,然后返回结果。您希望保持函数非常简单,并在函数之外执行所有逻辑和处理。这将消除对全局变量的需求,并使您的代码更易于阅读。

话虽如此,以下是我将如何解决您的问题:

import random  
def random_list(n=None):
  n = n or int(raw_input('How many numbers do you want in your list? '))    
  return [random.randint(1, n) for i in range(n)]
if __name__ == '__main__':
  my_list = random_list(10)
  minimum, maximum = min(my_list), max(my_list)
  print 'My list is ', my_list
  print 'The minimum value in the list is ', minimum
  print 'The maximum value in the list is ', maximum

以下是我的操作方法:

import random  
def main():
    # note that input can be dangerous since it evaluates arbitrary code
    n = int(raw_input("How many numbers do you want in your array?: "))
    my_list = [random.randint(1, n) for _ in range(n)]
    find_max_and_min(my_list)  
    the_smart_way(my_list)
def find_max_and_min(seq):
    print "My array is:", seq
    min_num = seq[0] # Don't want to use same names as bultins here
    for number in seq:
        if number < min_num:
            min_num = number
    print "The minimum value in the array is:", min_num
    max_num = seq[0]
    for number in seq:
        if number > max_num:
            max_num = number
    print "The maximum value in the array is:", max_num
def the_smart_way(seq):
    # "This one uses the built-in Python functions for min/max..."
    # No need for temp variables here
    print min(seq), max(seq)
if __name__ == '__main__':
    main()

相关内容

  • 没有找到相关文章

最新更新