vars()
如果对象具有__dict__属性,则vars()函数返回给定对象的__dict__属性.(函数返回对象object的属性和属性值的字典对象1 )

日常运用:
将args传递的参数从namespace 转换为dict,这样就不用将args包含的参数一一列举出来再传入相应函数中,化简代码,增加可读性.

class WGAN():def __init__(self,d1,d2):self.args = d1self.kwargs = d2def printval(self):print(self.args)print(self.kwargs)def parse_train():parser = argparse.ArgumentParser(description=”Tain WGAN model”)parser.add_argument(‘–try1′,dest=’d1’,default=1, type = int, help = “this is try1”)parser.add_argument(‘–try2′,dest=’d2’,default=2, type = int, help = “this is try2”)args = parser.parse_args()return argsdef main():args = parse_train()wgan = WGAN(**vars(args))wgan.printval()if __name__ == “__main__”:main() 若不用 wgan = WGAN(**vars(args)),则需要输入wgan = WGAN(args.d1,args.d2),在参数较多的情况下十分冗余,不便阅读

vars()
例子:

#1class checkvars(): def __init__(self,a,b): self.c = a self.d = 888 n = 777 self.y=0 def anther(self,x,y): self.x = x self.y = ytrytry = checkvars(1,2)print(vars(trytry))trytry.anther(5,6)print(vars(trytry))#2class checkvars(): def __init__(self,a,b): passtrytry = checkvars(1,2)print(vars(trytry))

结果:

#1{‘c’: 1, ‘d’: 888, ‘y’: 0}{‘c’: 1, ‘d’: 888, ‘y’: 6, ‘x’: 5}#2{}

思考:

如果vars()函数没有输入参数,用法与locals()相同,以字典形式返回当前位置的全部局部变量名(locals()用法移步(请移步基础函数locals))将类传递给vars(),返回此类下被声明部分所有变量名称,且子函数不会影响最终输出.运行函数表达式后,则会返回函数中改变的变量


http://www.runoob.com/python/python-func-vars.html ↩︎