python 两个内置函数——locals 和globals(名字空间)批量以自定义变量名创建对象
发布日期:2021-05-10 09:02:49 浏览次数:16 分类:精选文章

本文共 2349 字,大约阅读时间需要 7 分钟。

���������������������������Python������������������������������������globals()���������������������������������������������������locals()���������������������������������������������������������������������������������������������������������

������������������locals()������

������������������������locals()������������������������

def foo(arg, a):
x = 1
y = 'xxxxxx'
for i in range(10):
j = 1
k = i
print(locals()) # ������������������print������
foo(1, 2)

���������������������������������������������

{'arg': 1, 'a': 2, 'i': 9, 'k': 9, 'j': 1, 'y': 'xxxxxx', 'x': 1}

������������������locals()���������������������������������������������������������������������

������������������

���������������������������������������locals()���������������������������

import pyrealsense2 as rs
for i in range(10):
locals()['pipeline{}'.format(i)] = rs.pipeline()
print(locals()['pipeline{}'.format(i)])

������������������������������pipeline������������������������������������������������������������������������������

������������������������

���������������������������������������������

class A:
def __init__(self):
self.val = 10
for i in range(10):
locals()[f'x{i}'] = A()
print(locals()[f'x{i}'])

������������������������������������������������������������������A������������������������������������������������������������������������

������������������globals()������

���������������globals()���������������������������������

# -*- coding: utf-8 -*-
def fun():
globals()['a'] = 1
fun()
print(globals()['a'])

������������������������������a=1���������������������������������������

���������������������������

������������������������������������������������

class Bi:
def fun(self):
self.foo()
def foo(self):
globals()['a'] = 1
Bi().fun()
print(globals()['a'])

���������������������������������a������������print���������������������

������

���������������������������������globals()���locals()���������������������������������������������globals()���������������������������������������������locals()���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������

上一篇:Pycharm 项目文件名变红色以及commit时文件错乱的原因及解决办法
下一篇:python 并行、并发以及多线程的概念 tensorflow图像识别程序多线程并行

发表评论

最新留言

逛到本站,mark一下
[***.202.152.39]2025年04月27日 10时41分02秒