python里global_python – “global”和“import __main__”之间的区别

这与Python如何将代码转换为字节码(编译步骤)有关.

在编译函数时,Python会处理所有分配为局部变量的变量,并执行优化以减少必须执行的名称查找次数.每个局部变量都被赋予一个索引,当调用该函数时,它们的值将存储在由index寻址的堆栈本地数组中.编译器将发出LOAD_FAST和STORE_FAST操作码以访问变量.

全局语法指示编译器即使为变量赋值,也不应将其视为局部变量,不应为其分配索引.它将使用LOAD_GLOBAL和STORE_GLOBAL操作码来访问变量.这些操作码较慢,因为它们使用该名称在可能的许多字典(本地,全局)中进行查找.

如果仅访问变量以读取值,则编译器始终发出LOAD_GLOBAL,因为它不知道它是应该是本地变量还是全局变量,因此假设它是全局变量.

因此,在第一个函数中,使用全局x通知编译器您希望它将对x的写访问权视为写入全局变量而不是局部变量.该函数的操作码清楚地表明:

>>> dis.dis(changeXto1)

3 0 LOAD_CONST 1 (1)

3 STORE_GLOBAL 0 (x)

6 LOAD_CONST 0 (None)

9 RETURN_VALUE

在第三个示例中,将__main__模块导入名为__main__的局部变量,然后分配给其x字段.由于module是将所有顶级映射存储为字段的对象,因此您将在__main__模块中分配给变量x.正如您所发现的那样,__ main__模块字段直接映射到globals()字典中的值,因为您的代码是在__main__模块中定义的.操作码显示您不直接访问x:

>>> dis.dis(changeXto3)

2 0 LOAD_CONST 1 (-1)

3 LOAD_CONST 0 (None)

6 IMPORT_NAME 0 (__main__)

9 STORE_FAST 0 (__main__)

3 12 LOAD_CONST 2 (3)

15 LOAD_FAST 0 (__main__)

18 STORE_ATTR 1 (x)

21 LOAD_CONST 0 (None)

24 RETURN_VALUE

第二个例子很有趣.由于您为x变量赋值,编译器假定它是局部变量并进行优化.然后,from __main__ import x会导入模块__main__并创建一个新的绑定模块__main__中x的值到名为x的局部变量.这总是如此,从${module} import ${name}只需创建一个新的绑定当前命名空间.当您为变量x分配新值时,您只需更改当前绑定,而不是模块__main__中不相关的绑定(尽管如果值是可变的,并且您将其变异,则通过所有绑定可以看到更改).以下是操作码:

>>> dis.dis(f2)

2 0 LOAD_CONST 1 (-1)

3 LOAD_CONST 2 (('x',))

6 IMPORT_NAME 0 (__main__)

9 IMPORT_FROM 1 (x)

12 STORE_FAST 0 (x)

15 POP_TOP

3 16 LOAD_CONST 3 (2)

19 STORE_FAST 0 (x)

22 LOAD_CONST 0 (None)

25 RETURN_VALUE

考虑这一点的一个好方法是,在Python中,所有赋值都将名称绑定到字典中的值,而取消引用只是进行字典查找(这是粗略的近似,但非常接近概念模型).在做obj.field时,你正在查找隐藏的obj字典(可通过obj .__ dict__访问)为“field”键.

如果你有一个裸变量名,那么在locals()字典中查找它,然后在globals()字典中查找它(如果代码在模块级别执行则它们是相同的).对于赋值,它总是将绑定放在locals()字典中,除非您通过执行全局${name}声明您想要全局访问(此语法也适用于顶级).

所以翻译你的功能,这几乎是你写的:

# NOTE: this is valid Python code, but is less optimal than

# the original code. It is here only for demonstration.

def changeXto1():

globals()['x'] = 1

def changeXto2():

locals()['x'] = __import__('__main__').__dict__['x']

locals()['x'] = 2

def changeXto3():

locals()['__main__'] = __import__('__main__')

locals()['__main__'].__dict__['x'] = 3

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,我可以为你提供一个用 Python 设计的经典小游戏的源代码,比如俄罗斯方块。 ```python import pygame import random # 初始化pygame pygame.init() # 设置游戏窗口的大小 screen_width = 800 screen_height = 600 screen = pygame.display.set_mode((screen_width, screen_height)) pygame.display.set_caption('俄罗斯方块') # 定义颜色 BLACK = (0, 0, 0) WHITE = (255, 255, 255) RED = (255, 0, 0) GREEN = (0, 255, 0) BLUE = (0, 0, 255) # 定义方块的大小 block_size = 20 # 定义游戏区域大小 play_width = 10 * block_size play_height = 20 * block_size # 定义游戏区域的位置 play_x = (screen_width - play_width) // 2 play_y = screen_height - play_height - 50 # 定义字体 font = pygame.font.SysFont(None, 30) # 定义方块类 class Block: def __init__(self, x, y, color): self.x = x self.y = y self.color = color # 定义方块形状 block_shapes = [ [[1, 1, 1], [0, 1, 0]], [[0, 2, 2], [2, 2, 0]], [[3, 3, 0], [0, 3, 3]], [[4, 0, 0], [4, 4, 4]], [[0, 0, 5], [5, 5, 5]], [[6, 6, 6, 6]], [[7, 7], [7, 7]] ] # 随机生成方块 def new_block(): shape = random.choice(block_shapes) block = [] for i in range(len(shape)): row = [] for j in range(len(shape[i])): if shape[i][j] != 0: row.append(Block(j, i, shape[i][j])) block.append(row) return block # 初始化游戏 def init_game(): global play_area, current_block, next_block, score play_area = [[0] * 10 for _ in range(20)] current_block = new_block() next_block = new_block() score = 0 # 绘制游戏区域 def draw_play_area(): for i in range(len(play_area)): for j in range(len(play_area[i])): if play_area[i][j] != 0: pygame.draw.rect(screen, colors[play_area[i][j]], (play_x + j * block_size, play_y + i * block_size, block_size, block_size), 0) # 绘制方块 def draw_block(block, x, y): for i in range(len(block)): for j in range(len(block[i])): if block[i][j] != 0: pygame.draw.rect(screen, colors[block[i][j]], (x + j * block_size, y + i * block_size, block_size, block_size), 0) # 绘制下一个方块 def draw_next_block(): pygame.draw.rect(screen, WHITE, (play_x + play_width + 20, play_y, block_size * 4, block_size * 4), 0) draw_block(next_block, play_x + play_width + 30, play_y + 10) # 绘制得分 def draw_score(): score_text = font.render('Score: ' + str(score), True, WHITE) screen.blit(score_text, (play_x + play_width + 20, play_y + 100)) # 判断方块是否可以移动 def can_move(block, x, y): for i in range(len(block)): for j in range(len(block[i])): if block[i][j] != 0: if x + j < 0 or x + j >= 10 or y + i >= 20 or play_area[y + i][x + j] != 0: return False return True # 将方块加入游戏区域 def add_block_to_play_area(block, x, y): for i in range(len(block)): for j in range(len(block[i])): if block[i][j] != 0: play_area[y + i][x + j] = block[i][j] # 判断是否有满行 def check_full_lines(): lines = [] for i in range(len(play_area)): if 0 not in play_area[i]: lines.append(i) return lines # 删除满行 def remove_full_lines(lines): global score for line in lines: play_area.pop(line) play_area.insert(0, [0] * 10) score += 10 * len(lines) # 主循环 def main_loop(): global current_block, next_block, score clock = pygame.time.Clock() fall_time = 0 fall_speed = 0.5 game_over = False while not game_over: for event in pygame.event.get(): if event.type == pygame.QUIT: game_over = True if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: if can_move(current_block, current_block_x - 1, current_block_y): current_block_x -= 1 if event.key == pygame.K_RIGHT: if can_move(current_block, current_block_x + 1, current_block_y): current_block_x += 1 if event.key == pygame.K_UP: rotated_block = list(zip(*current_block[::-1])) if can_move(rotated_block, current_block_x, current_block_y): current_block = rotated_block if event.key == pygame.K_DOWN: if can_move(current_block, current_block_x, current_block_y + 1): current_block_y += 1 fall_time += clock.get_rawtime() clock.tick() if fall_time / 1000 >= fall_speed: if can_move(current_block, current_block_x, current_block_y + 1): current_block_y += 1 else: add_block_to_play_area(current_block, current_block_x, current_block_y) lines = check_full_lines() if lines: remove_full_lines(lines) current_block = next_block next_block = new_block() current_block_x = 3 current_block_y = 0 if not can_move(current_block, current_block_x, current_block_y): game_over = True fall_time = 0 screen.fill(BLACK) draw_play_area() draw_block(current_block, play_x + current_block_x * block_size, play_y + current_block_y * block_size) draw_next_block() draw_score() pygame.display.flip() pygame.quit() # 开始游戏 colors = [BLACK, RED, GREEN, BLUE, WHITE] init_game() current_block_x = 3 current_block_y = 0 main_loop() ``` 这是一个简单的俄罗斯方块游戏,可以在 Pygame 中运行。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值