如何在不使用全局函数的情况下在代码中引用局部变量

时间:2016-07-05 05:04:35

标签: python pygame python-3.4

我正在为我正在进行的游戏制作库存系统,到目前为止我已经为系统编写了这些代码块。我希望系统在不使用全局函数的情况下工作,因为我已经读过你应该避免使用全局函数。

while not done:
    global inventory
    pygame.mouse.set_visible(False)
    #Event processing
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True
    elif event.type == pygame.KEYDOWN:
        if event.key == pygame.K_i:
             inv_sys.inventory = True
             inv_sys.inventory_u()

import pygame
import Constants

clock = pygame.time.Clock()
screen = pygame.display.set_mode(Constants.screen_size)
inv = pygame.image.load("inv.png").convert()
test = False

def uninventory():
    global inventory
    inventory = False

def inventory_u():

    while inventory:
        pygame.mouse.set_visible(True)
        screen.blit(inv,(0,0))
        for event in pygame.event.get():

            if event.type == pygame.QUIT:
                pygame.quit
            elif event.type == pygame.KEYDOWN:    
                if event.key == pygame.K_i:
                     uninventory()

         pygame.display.update()
         clock.tick(60)

提前感谢您的任何帮助!

3 个答案:

答案 0 :(得分:2)

  

因为我已经读过你应该避免使用[全局陈述]

我认为你误解了。 global关键字本身并不坏。相反,如果您的实现需要使用 global关键字,那么您的实现很糟糕(在大多数情况下,尽管可能有例外)。您应该尝试将变量传递给函数,而不是使用全局范围的变量编写代码。

def main():
    eels = 42
    start_hovercraft(eels)

def start_hovercraft(number_of_eels):
    if number_of_eels > 3:
        raise Exception("My hovercraft is full of eels!")

@ PatNowak关于使用课程的建议也是解决问题的好方法,但问题的关键是你应该尽可能避免使用global,因为它会导致错误的代码:

答案 1 :(得分:1)

一般情况下,如果您经常引用其值已分配一次且未更改的变量,请根据PEP 8 style guide在文件顶部附近的模块范围内定义它,因此对于阅读您的任何人来说,这显然是一个常数码。您的import语句也应位于文件的顶部。

如果你在程序中引用并且用来改变程序的状态,就像使用global inventory一样,它(以及引用它的方法)可能应该是类定义的一部分PatNowak描述了将变量作为属性。您可以在类的内部或外部引用这些方法(分别使用self或类实例),但属性本身只能在类中直接更改,否则您的代码很快就无法调试或重写。 / p>

global关键字有其用途,但我从来没有理由使用它而不是其他两种方法中的一种。

答案 2 :(得分:0)

考虑为什么要在许多函数之间共享一个局部变量? 也许更好的方法是简单地创建一个类,其中inventory或更具描述性的东西将作为对象变量。

class MyGame:
    def __init__():
        # something
        self.inventory = True
    # some code
    def unEquip():
        self.inventory = False