Python替代全局变量 [英] Python Alternatives to Global Variables

查看:123
本文介绍了Python替代全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 导入随机

#--------------------------- -------------------#
def main():
create_list_and_find_max_and_min(10)
the_smart_way()
# - ---------------------------------------------#
高清create_list_and_find_max_and_min(N):
全球my_array
my_array = [] $ b $ = BN输入( 你希望你的阵列?:多少个数字办)
为我的range( n):
my_array.append(random.randint(1,n))
print我的数组是:,my_array
#------------ ----------------------------------#
min = my_array [0]
for number in my_array:
if min> number:
min = number
print数组中的最小值是:,min
#------------------- ---------------------------#
max = my_array [0]
在my_array中的数字:
如果max < number:
max = number
print数组中的最大值为:,max
#------------------- ---------------------------#
def the_smart_way():
#这个使用内建的最小/最大Python函数...
min_my_array =分钟(my_array)
max_my_array = MAX(my_array)
返回min_my_array,max_my_array
#------- ---------------------------------------#
if __name__ =='__main__ ':
main()

我对使用Python相当陌生。我一般都听说在编程时使用全局变量是一种不好的做法。所以有什么替代方案可以让我在这里做什么。哪个是从另一个函数内部使用变量my_array?谢谢!

解决方案

是的,有两种选择。 ,你可以传递值而不是使用全局变量。例如,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(你想在你的数组中有多少个数字:)
在范围(n)中:i
my_array.append(random.randint(1,n ))
print我的数组是:,my_array
#------------------------------ ----------------#
min = my_array [0]
用于my_array中的数字:
if min> number:
min = number
print数组中的最小值是:,min
#------------------- ---------------------------#
max = my_array [0]
在my_array中的数字:
如果max < number:
max = number
print数组中的最大值为:,max
return my_array
#------------- ---------------------------------#
def the_smart_way(my_array):
#这一个使用内置的Python功能最小/最大...
min_my_array =分钟(my_array)
max_my_array = MAX(my_array)
返回min_my_array,max_my_array
# ----------------------------------------------#
if __name__ =='__main__':
main()

其次,您可以创建一个封装数据的类以及对这些数据进行操作的函数:

  import random 

# ----------------------------------------------#
类MyArrayClass(对象):
高清create_list_and_find_max_and_min(个体经营,N):
self.my_array = [] $ b $ = BN输入( 多少号,你希望你的数组中?:)
为范围(n)中的i:
self.my_array。 append(random.randint(1,n))
print我的数组是:,self.my_array
#------------------- ---------------------------#
min = self.my_array [0]
代表self.my_array中的数字:
if min> number:
min = number
print数组中的最小值是:,min
#------------------- ---------------------------#
max = self.my_array [0]
为self.my_array中的数字:
如果最大值< number:
max = number
print数组中的最大值为:,max
#------------------- ---------------------------#
def the_smart_way(self):
#在Python功能最小/最大...
min_my_array =分钟(self.my_array)
max_my_array = MAX(self.my_array)
返回min_my_array,max_my_array
# - --------------------------------------------#
def主():
my_array = MyArrayClass()
my_array.create_list_and_find_max_and_min(10)
打印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)
#无法在原始数组上操作!

使用本地变量,您可以存储它们两个:



'pre> 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 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()

I'm fairly new to using Python. I've generally heard that using global variables is a bad practice when programming.. So are there any alternatives to what I'm trying to do here. Which is to use the variable "my_array" from inside another function? Thanks!

解决方案

Yes, there are two alternatives.

First, you can pass the values around instead of using globals. For example, create_list_and_find_max_and_min can create the array locally and return it, then you can pass it in to 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()

Second, you can create a class that encapsulates the data and the functions that operate on that data:

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()

You should probably understand the reasons global variables are bad practice.

Imagine that you want to create two arrays. With global variables, the second one will replace the first one, which will be gone forever.

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

With a local variable, you can store both of them:

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)

Using an object provides the same benefit; the difference between the two ultimately comes down to whether the operations are part of the meaning of the data, or whether the data stand alone and the operations are generic. (Or, sometimes, whether you're more of a functional snob or an OO snob…)

这篇关于Python替代全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆