2016-07-05 64 views
0

我正在为我正在处理的游戏编制库存系统,至此我已为系统编写了这些代码块。我希望系统在不使用全局函数的情况下工作,因为我已经读过,应该避免使用全局函数。如何在不使用全局函数的情况下在我的代码中引用局部变量

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) 

提前谢谢你的帮助!

回答

0

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

class MyGame: 
    def __init__(): 
     # something 
     self.inventory = True 
    # some code 
    def unEquip(): 
     self.inventory = False 
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

一般而言,如果您经常引用一个变量,其值只能分配一次而没有更改,请根据PEP 8 style guide将其定义在靠近文件顶部的模块范围内,因此对于任何读取您的代码的人来说,它显然是不变的。您的进口报表也应该位于文件的顶部。

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

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

相关问题