locals() trả về dictionary biến khai báo trong local scope, globals() trả về dictionary biến khai báo trong global scope. Ở global scope, cả locals() và globals() trả về cùng dictionary global namespace. Để thấy khác biệt, gọi từ trong function. Ví dụ:
def fun():
var = 123
print "Locals: ", locals()
print "Vars: ", vars()
print "Globals: ", globals()
fun()
Output:
Locals: {'var': 123}
Globals: {'__builtins__': , '__name__': '__main__', 'fun': , '__doc__': None, '__package__': None}
vars() trả về dictionary current namespace (nếu gọi không argument) hoặc dictionary của argument. Khác biệt chính locals() và vars() là vars() cũng nhận argument và trả về dictionary cho object yêu cầu. Ví dụ, muốn attribute của object trong dict, truyền object đó lấy attribute dict cho instance.
vars() cho object tương tự property __dict__ của object đó. __dict__ trả về tất cả attribute định nghĩa cho object. Ví dụ:
class A():
def __init__(self, id):
self.id = id
a = A(1)
print "__dict__: ", a.__dict__
print "vars(a): ", vars(a)
Output:
__dict__: {'id': 1}
vars(a): {'id': 1}