# -*- coding: utf-8 -*-
# @File : builtin-vars-example.py
# @Date : 2018-09-20
# @Author : Peng Shiyu
# vars 返回包含每个成员当前值的字典
from pprint import pprint
name = "哈利波特"
age = 24
pprint(vars())
"""
{'__builtins__': <module '__builtin__' (built-in)>,
'__doc__': None,
'__file__': '/example/builtin-vars-example.py',
'__name__': '__main__',
'__package__': None,
'age': 24,
'name': '\xe5\x93\x88\xe5\x88\xa9\xe6\xb3\xa2\xe7\x89\xb9',
'pprint': <function pprint at 0x104580aa0>}
"""
print("%(name)s yeas old is %(age)s" % vars())
# 哈利波特 yeas old is 24
# locals 返回当前局部名称空间的可见元素
pprint(locals())
"""
{'__builtins__': <module '__builtin__' (built-in)>,
'__doc__': None,
'__file__': '/example/builtin-vars-example.py',
'__name__': '__main__',
'__package__': None,
'age': 24,
'name': '\xe5\x93\x88\xe5\x88\xa9\xe6\xb3\xa2\xe7\x89\xb9',
'pprint': <function pprint at 0x10a84baa0>}
"""
"""
总结:
vars()
Without arguments, equivalent to locals().
With an argument, equivalent to object.__dict__.
locals()
Update and return a dictionary containing the current scope's local variables.
"""
pprint(globals())
"""
{'__builtins__': <module '__builtin__' (built-in)>,
'__doc__': None,
'__file__': '/example/builtin-vars-example.py',
'__name__': '__main__',
'__package__': None,
'age': 24,
'name': '\xe5\x93\x88\xe5\x88\xa9\xe6\xb3\xa2\xe7\x89\xb9',
'pprint': <function pprint at 0x1065d5b18>}
"""
# 获取实例对象的属性
class A(object):
def __init__(self):
self.a = 1
self.b = 2
def keys(self):
for key in vars(self).keys():
yield key
def get_keys(self):
for key in self.__dict__:
yield key
a = A()
for key in a.keys():
print(key)
for key in a.get_keys():
print(key)