eval
执行表达式
exec
执行语句
globals
全局变量
locals
局部变量
vars
类的成员
i = 0
exec('j = 0')
print(globals())
{'__name__': '__main__',
...
'i': 0,
'j': 0}
class Dummy(object):
def __init__(self) -> None:
self.i = 0
exec('self.j = 0')
dummy = Dummy()
print(vars(dummy))
{'i': 0, 'j': 0}
class EasyArgs(object):
def __init__(self, **kvps):
self.add(**kvps)
def add(self, **kvps): # 函数参数名转化成字符串(字典的键)
for k,v in kvps.items():
exec(f'self.{k} = None') # 字符串转化成示例的成员变量名
vars(self)[k] = v
if __name__ == '__main__':
args = EasyArgs(batch_size = 32)
args.add(epochs = 64)
print(vars(args)) # 成员变量名转化成字符串
print(args.batch_size) # 直接根据成员变量名使用变量
print(args.epochs)
{'batch_size': 32, 'epochs': 64}
32
64